我被派去制作一张横过大西洋的飓风以及它们的风速,压力等表格。我正在对其进行测试,以确保inFile扫描仪可以正常工作,但始终出现错误
我尝试抛出Exception,抛出NoSuchElementException,将int更改为Strings(不确定为什么我认为这可行)
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();
任何有关我的错误的帮助都将受到感谢
答案 0 :(得分:1)
由于while循环,您的扫描仪指向文件的最后一行,并且您尝试读取的是同一行
year[n] = inFile.nextInt();
由于没有扫描器指向的元素,因此导致异常。