I am trying to get a Scanner to read the input of a text file, have that input put into a String, have a StringTokenizer of that String, and then have a String[] with each element of that array being a token of that StringTokenizer. The purpose of this is to get a String[] of the inputted text from the text file such that each element of the array is a word in the text file. However, the code I have so far generates a NoSuchElementFound Exception.
Scanner f = new Scanner( "input.txt" ); // Yes, I have the file path here, I changed it though.
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt" );
String temp = "";
String cString = "";
while( ( cString = f.nextLine() ) != null ) { // Line where exception occurs
temp += cString;
}
StringTokenizer everythingTokens = new StringTokenizer( temp );
String[] everything = new String[ everythingTokens.countTokens() ];
for( int i = 0; i < everything.length; i++ ) {
everything[ i ] = everythingTokens.nextToken();
}
out.println( everything[ 0 ] );
Here is the error message
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at gift1.main(gift1.java:21)
Java Result: 1
The input for this in the text file is
Hey,
How are you?
Why is this happening and how can I fix it?
That’s not how you use a Scanner. You’d instead do:
Please have a look at the Scanner API and you’ll see that it doesn’t return null if it runs out of lines. Instead it throws a …. NoSuchElementException. I think that you’re confusing its use with that of a BufferedReader, and they’re really two completely distinct species.