【发布时间】:2016-01-08 02:29:43
【问题描述】:
我已经阅读了几篇关于如何将 txt 文件读入 int[] 的文章,并且通过多种可能的方式我没有成功。
import java.io.*;
import java.util.Scanner;
public class SequenceSquare
{
private int[] arr;
public SequenceSquare()
{
int count = 0;
File fileName = new File("Sequence.txt"); // fileName for opening
try
{
Scanner input = new Scanner(fileName);
while (input.hasNextLine()) //while there is a line to read
{
if(input.hasNextInt()) //if this line has an int
{
count++; // increment count
input.nextInt(); //move to next integer
}
}
arr = new int[count]; // create arr with sufficient size
input.close(); // close scanning file
Scanner newInput = new Scanner(fileName);
for(int i = 0; i < arr.length; i++)
{
while (newInput.hasNextLine()) // same as above
{
if(newInput.hasNextInt()) // same as above
{
arr[i] = newInput.nextInt(); //store int scanned into arr
}
}
}
newInput.close();
}
catch(FileNotFoundException f)
{
f.printStackTrace();
}
}
"Sequence.txt"
1
2
5
9
29
30
7
9
111
59
106
130
-2
所以基本上当调用默认构造函数时,假设打开“Sequence.txt”并读取格式化为 int 数组的整数。在 txt 文件中,数字被格式化为每行的整数,例如4\n 5\n 等 但是,当我遍历数组“arr”时,它似乎没有内容。我已经实现了许多测试函数来测试是否已填充(未列出)但 arr 没有返回任何内容。请帮忙。请告诉我发生了什么。我宁愿知道对正在发生的事情的解释而不是答案,但两者都可以。另外我知道您可以使用数组列表和列表来执行相同的功能,但我希望它是一个数组。如果您想查看我可以发布的整个课程,但其他代码是不必要的,因为它可以工作
【问题讨论】:
-
显示
Sequence.txt文件 -
是一行一行的。当您类似地发布代码时,您可以文本文件内容
-
你可以用列表代替数组吗?
-
我可以使用列表或数组列表,但我更喜欢使用数组来学习。
-
您的 Sequence.txt 应该有问题。因为它完美地为我工作。确保您在其他路径中没有相同的命名文件。我刚刚在
arr[i] = newInput.nextInt()中分配了数组元素后打印了它
标签: java arrays io int java.util.scanner