In Java, I'm getting this Exception:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at com.reading.text.Activity3.readFile(Activity3.java:22)
at com.reading.text.Activity3.main(Activity3.java:10)
From this Java code:
public static void main(String args[])
{
readFile("C:/Users/forsakendoll/Desktop/boom.txt");
}
public static void readFile(String path) {
Scanner file = null;
try {
file = new Scanner(new File (path));
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
while (file.hasNext()) {
for(int counter = 0 ; counter < file.next().length(); counter ++) {
System.out.println(file.next().charAt(counter));
}
}
}
}
The Exception is thrown on
System.out.println(file.next().charAt(counter));
What does the Exception mean?
Don't call next() so much times! It actually go to the next element when you call it. If you need to use it more than once, put it inside a variable and use it.
You are calling
.next()
twice on every iteration of the loop, so when you are near the end, you jump off the end of the list and the compilter tells you there is nothing there.Instead of this:
Do this instead:
SEE HERE
The Scanner.next() method will move the internal iterator along one. Your code should be: