gpt4 book ai didi

java - "hasNextInt()"扫描仪问题

转载 作者:行者123 更新时间:2023-11-29 05:24:36 30 4
gpt4 key购买 nike

我有一个文件,每一行都有不同的整数。例如:

5
4
3
2
1

我正在尝试编写一个程序来遍历每个 int,并将该 int 放入一个数组中。到目前为止,我的代码是:

      Scanner sc = new Scanner(args[0]);

BufferedReader reader = new BufferedReader(new FileReader(args[0]));
lines = 0;
while (reader.readLine() != null) lines++;
reader.close();

intArray = new int[lines];

int counter = 0;
while(sc.hasNextInt()) {
intArray[counter] =sc.nextInt();
counter++;
}

我的程序创建了具有正确数量索引的数组,但它永远不会进入扫描器的 while 循环。我不知道这是为什么,因为根据这个 page 看起来我有相同的代码.

最佳答案

除非您的文件路径是空格分隔的数字,否则您不会得到任何数字。 扫描器 was scanning the file path (作为 String),而不是文件。

Scanner sc = new Scanner(new FileInputStream(args[0]));

仅供引用,如果您使用 List 而不是读取文件两次会更清楚。

关于java - "hasNextInt()"扫描仪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23172447/

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