简体   繁体   中英

Keep getting the java.util.NoSuchElementException on this program

I am currently writing a program that writes class codes to a file and then reads them back from said file and prints them to the screen. Everytime I run the program I keep getting the java.util.NoSuchElementException. This problem persists after every modification I have made and I'm not sure where to go from here. Any help would be greatly appreciated.

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();   
    }
}

}

And after running the program:

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)

Once there are no more elements left to read, the Scanner will throw the exception you are seeing. Right now you continue to loop while you can read the file, but that has no bearing on where the Scanner is in the file. Scanner provides a family of functions to check the validity of the next tokens: hasNext() , hasNextInt() , hasNextLine() , etc. You should use these instead:

while( input.hasNext() ) {
    String code = input.next();
    // ...
}

However, if you have a malformed file, you could still get the exception for similar reasons reading the hours and titles. You can handle these by checking the scanner before reading them, or possibly in an exception handler since this probably indicates a larger problem, such as reading an unsupported or corrupt file.

  • Please call Scanner.hasNext() , so that the loop will terminate when there are no more elements.

  • Don't close input explicitly as you are using the try-with-resources which will take care of it.

  • There is no need of two separate try blocks, as they could be combined together, once the writing is finished use the PrintWriter.flush() to write it to disk.

     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);Scanner input = new Scanner(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"); output.flush(); while (file.canRead() && input.hasNext()) { String code = input.next(); int creditHours = input.nextInt(); String courseTitle = input.nextLine(); System.out.println("Course Code = " + code + " | Credit Hours = " + creditHours + " | Course Title = " + courseTitle); } } } } 

file.canRead() will always return true and when read pointer reaches EOF, next input.read() operation fails.

Use input.hasNextLine() to check if EOF is reached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM