英文:
How to read integers to array from file
问题
static int[] readFromFile() {
int[] data = new int[10];
try {
File myObj = new File("inputFile.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for(int i = 0; i < data.length; i++)
data[i] = myReader.nextInt();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println(" .");
e.printStackTrace();
}
return data;
}
我想让这段代码返回从文件中读取的整数数组。
英文:
So, basically I want to learn how to read from file integers using methods and get the output - array to return. Does someone have an advice?
static int[] readFromFile() {
int[] data = new int[10];
try {
File myObj = new File("inputFile.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for(int i = 0; i < data.length; i++)
data[i] = myReader.nextInt();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println(" .");
e.printStackTrace();
}
return data;
}
I want that code returns arrays with all integers from file
答案1
得分: 1
你有几个问题。一个是你无法更改数组的大小。如果要调整大小,您将需要重新分配一个新数组并复制数据。
另一个问题是您有两个循环在进行。每次调用 while 循环时,都会覆盖你的包含 10 个元素的数组。
因此,让我们尝试使用 ArrayList。ArrayList 允许您动态地将更多项附加到末尾。
编辑:您只想要 10 个整数:
static List<Integer> readFromFile() {
List<Integer> data = new ArrayList<>();
try {
File myObj = new File("inputFile.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNext() && data.size() < 10) {
data.add(myReader.nextInt());
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println(" .");
e.printStackTrace();
}
return data;
}
如果在所有这些操作结束后,您真的想要返回数组而不是列表,您可以在 data
上使用 toArray()
方法。
英文:
You have a couple of problems. One is that you cannot change the size of an array. You would have to reallocate a new array and copy if you want to resize it.
The other is that you have two loops going on. Every invocation of the while loop will overwrite your array of 10 elements.
So let's try using ArrayList instead. ArrayList lets you dynamically append more items onto the end.
Edit: you only want 10 integers:
static List<Integer> readFromFile() {
List<Integer> data = new ArrayList<>();
try {
File myObj = new File("inputFile.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNext() && data.size() < 10) {
data.add(myReader.nextInt());
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println(" .");
e.printStackTrace();
}
return data;
}
If, at the end of all that, you really want to return an array instead of a list, you can use the toArray()
method on data
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论