gpt4 book ai didi

java - 将文件中的数字读入数组时遇到问题

转载 作者:行者123 更新时间:2023-12-01 19:33:28 26 4
gpt4 key购买 nike

numbers.txt 文件中有 26 个数字。这 26 个数字应该被读取到 arr,但我在数组中得到了 26 个零。

Scanner scanner = new Scanner(new File("numbers.txt"));
int n = 0;
int i = 0;
while (scanner.hasNextInt()) {
scanner.next();
n++;
} // n is now 26
int[] arr = new int[n];
while (scanner.hasNextInt()) {
for (i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
}
}
System.out.print(Arrays.toString(arr));

最佳答案

零是数组的默认值。扫描仪是“一次性”的,它是单次通过的。如果您使用过它一次,则必须创建另一个(也许之前将 File 对象放在变量中,然后使用它来创建两个 Scanner ?)或者以某种方式反转它状态。第二个循环的迭代次数为零,它再也不会 hasNextInt

关于java - 将文件中的数字读入数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58666917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com