我接到的任务是制作一张大西洋飓风表,以及它们的风速、压力等,我正在对其进行测试以确保扫描仪 inFile 正常工作,但不断出现错误我尝试过抛出异常,抛出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]); } }}它应该打印出整数和字符串,但我却收到了这个错误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();任何有关我的错误的帮助将不胜感激
1 回答
倚天杖
TA贡献1828条经验 获得超3个赞
由于 while 循环,您的扫描仪指向文件的最后一行,并且在您尝试读取的同一行中
year[n] = inFile.nextInt();
这导致异常,因为没有扫描仪指向的元素。
添加回答
举报
0/150
提交
取消