扫描仪正在创建一个 NoSuchElementException 错误,我不明白为什么
Scanner is creating a NoSuchElementException error, and I can't figure out why
我的任务是制作 table 大西洋上空的飓风,以及它们的风速、压力等。我正在对其进行测试,以确保文件中的扫描仪正常工作,但一直在运行一个错误
我试过抛出异常,抛出 NoSuchElementException,将整数更改为字符串(不确定为什么我认为这会起作用)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
File data = new File("C:\Users\zenno\OneDrive\Documents\School\Hurricane Data\hurcdata2.txt");
Scanner inFile = new Scanner (data);
int length = 0;
while (inFile.hasNextLine()){
length++;
inFile.nextLine();
}
int[] year = new int[length];
String[] month = new String[length];
int[] pressure = new int[length];
int[] speed = new int[length];
String[] name = new String[length];
for(int n = 0; n <= length; n++){
year[n] = inFile.nextInt();
month[n] = inFile.next();
pressure[n] = inFile.nextInt();
speed[n] = inFile.nextInt();
name[n] = inFile.next();
System.out.println(year[n] + " " + month[n] + " " + pressure[n] + " " + speed[n] + " " + name[n]);
}
}
}
它应该打印出 int 和字符串,但我却收到了这个错误
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:25)
第 25 行是:
year[n] = inFile.nextInt();
任何关于我的错误的帮助将不胜感激
由于 while 循环,您的扫描仪指向文件的最后一行,并且在您尝试读取的同一行中
year[n] = inFile.nextInt();
这是导致异常的原因,因为没有扫描仪指向的元素。
我的任务是制作 table 大西洋上空的飓风,以及它们的风速、压力等。我正在对其进行测试,以确保文件中的扫描仪正常工作,但一直在运行一个错误
我试过抛出异常,抛出 NoSuchElementException,将整数更改为字符串(不确定为什么我认为这会起作用)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
File data = new File("C:\Users\zenno\OneDrive\Documents\School\Hurricane Data\hurcdata2.txt");
Scanner inFile = new Scanner (data);
int length = 0;
while (inFile.hasNextLine()){
length++;
inFile.nextLine();
}
int[] year = new int[length];
String[] month = new String[length];
int[] pressure = new int[length];
int[] speed = new int[length];
String[] name = new String[length];
for(int n = 0; n <= length; n++){
year[n] = inFile.nextInt();
month[n] = inFile.next();
pressure[n] = inFile.nextInt();
speed[n] = inFile.nextInt();
name[n] = inFile.next();
System.out.println(year[n] + " " + month[n] + " " + pressure[n] + " " + speed[n] + " " + name[n]);
}
}
}
它应该打印出 int 和字符串,但我却收到了这个错误
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:25)
第 25 行是:
year[n] = inFile.nextInt();
任何关于我的错误的帮助将不胜感激
由于 while 循环,您的扫描仪指向文件的最后一行,并且在您尝试读取的同一行中
year[n] = inFile.nextInt();
这是导致异常的原因,因为没有扫描仪指向的元素。