我正在尝试从文件中读取无空格整数列表,但我不明白为什么我永远无法通过 while 循环中的条件。
这是整个“nums.txt”文件:
12121212121212121212121212121212
00001212121212121212121212121212
33331212121212121212121212121212
这个小脚本看起来像这样:
import java.util.Scanner;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Test{
public static void main(String[] args){
try{
Scanner reader = new Scanner(new BufferedReader(new FileReader(new File("nums.txt"))));
while(reader.hasNextInt()){
System.out.println(reader.nextInt());
}
reader.close()
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
运行时,不输出任何内容并终止。
最佳答案
根据其JavaDoc Scanner.hasNextInt()
:
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method.
12121212121212121212121212121212
是下一个标记,它不能被解释为 int,因为最大 int 为 2147483647。
因此 hasNextInt()
返回 false
,循环结束。
扫描器
本质上适用于由分隔符(默认情况下为空格)分隔的标记。如果您想一次使用一个字符,请使用 Reader.read()
甚至 InputStream.read()
。
关于java - 读取无空格整数的文件 - hasNextInt() 永远不会返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43897822/