我目前正在编写一个程序,它将类代码写入文件,然后从所述文件中读回它们并将它们打印到屏幕上。每次运行该程序时,我都会收到 java.util.NoSuchElementException。在我进行每次修改后,这个问题仍然存在,我不知道从这里该去哪里。任何帮助将不胜感激。
package u2a1_readtextfilehandleexcep;
import java.io.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class U2A1_ReadTextFileHandleExcep {
public static void main(String[] args) throws FileNotFoundException, IOException {
//Create new file called course.txt
java.io.File file = new java.io.File("course.txt");
if (file.exists()) {
System.out.println("File already exists; try another name.");
System.exit(0);
}
//Input the specified words to the file
try (PrintWriter output = new PrintWriter(file)) {
output.println("IT2249 6 Introduction to Programming with Java");
output.println("IT2230 3 Introduction to Database Systems");
output.println("IT4789 3 Mobile Cloud Computing Application Development");
}
try (
//Reads from file to the console
Scanner input = new Scanner(file)) {
while (file.canRead()) {
String code = input.next();
int creditHours = input.nextInt();
String courseTitle = input.nextLine();
System.out.println("Course Code = " + code + " | Credit Hours = " + creditHours + " | Course Title = " + courseTitle);
}
input.close();
}
}
}
运行程序后:
Course Code = IT2249 | Credit Hours = 6 | Course Title = Introduction to Programming with Java
Exception in thread "main" java.util.NoSuchElementException
Course Code = IT2230 | Credit Hours = 3 | Course Title = Introduction to Database Systems
Course Code = IT4789 | Credit Hours = 3 | Course Title = Mobile Cloud Computing Application Development
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at u2a1_readtextfilehandleexcep.U2A1_ReadTextFileHandleExcep.main(U2A1_ReadTextFileHandleExcep.java:26)
C:\Users\Deb\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
最佳答案
一旦没有更多元素可供读取,扫描器
将抛出您所看到的异常。现在,您可以在读取文件的同时继续循环,但这与 Scanner
在文件中的位置无关。 Scanner
提供了一系列函数来检查下一个标记的有效性:hasNext()
、hasNextInt()
、hasNextLine()
等。您应该使用这些:
while( input.hasNext() ) {
String code = input.next();
// ...
}
但是,如果您有格式错误的文件,您仍然可能会因为类似的原因而在阅读时间和标题时遇到异常。您可以通过在读取它们之前检查扫描仪来处理这些问题,或者可能在异常处理程序中进行处理,因为这可能表明存在更大的问题,例如读取不受支持或损坏的文件。
关于java - 在此程序上继续获取 java.util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52019572/