我有一个txt,我想扫描它,每次读取一个整数时,我都想将它输入到我已经创建的数组中。
每当读取 int 以外的内容(例如 String、double 甚至空行)时,如何抛出异常?
这就是我读取文件并完成数组的方式:
file= new Scanner(new File(file_name));
int[] txt = new int[cnt]; // cnt , the number of lines in my txt
while ( file.hasNextInt()) {
txt[count] = file.nextInt();
count++;
}
谢谢:)
最佳答案
将 hashNextInt()
更改为 hasNext()
,您将收到请求的异常,
while (file.hasNextInt()) {
至
while (file.hasNext()) {
关于如果文件具有无效值/字符,Java 会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47934476/