0
Mistake in exercise?
In the last exercise for files, there is a while (scanner.hasNext ()) followed by two scanner.next (). Why check if there is a next and then ask for two nexts?
7 Réponses
0
No error. The next method returns a token in the file. The tokens in the example are string. The code is saying, while(there are still strings)
String 1 = first token/word
String 2 = second token/word
Then print them out.
For each token in a file, you have to call next if you are to place it in a variable.
0
Agree, but you are checking for one string and asking for two before checking if there are more than one
0
You are not checking for one. The while loop is saying hasNext, meaning if there are still any tokens, keep running. If you checked for just one, then the second String b wouldnt work.
If you mean having two strings asked for with the possibility there is only one token in the file? Then yes, a poor choice. But the idea is set as an example. Obviously, it would be better to use an array or list, but the tutorial is just giving an example of what can be done
Like if you knew what was in the file, for example. And you want each word to be a different string entirely and didn't want it part of a list or array. It'd be useful then.
0
I went out and tested it and it throws an exception as expected. Try this out:
import java.util.Scanner;
class MyClass {
public static void main(String[ ] args) {
Scanner myVar = new Scanner(System.in);
while (myVar.hasNext()) {
System.out.println(myVar.next());
System.out.println(myVar.next());
}
}
}
And enter a few words when prompted.
no exception would be thrown if after the hasNext() check, only one next() is asked for.
I believe that for an example, the latter approach should be better, as it avoids the unnecessary exception, don't you think?
0
It throws an exception because you're using code playground. The playground ONLY accepts any and all inputs when you first run it. It will not ask for more inputs later in the program. Try putting both inputs in the initial box. Works. Try running your code on an actual ide or command prompt. Works.
0
Will try and get back to you. thanks :-)
0
Ok, so I've tried putting in the IDE the code from the last "Reading from files" exercise I was referring to, and using a text file with 5 words, output just shows 4 of the words and a null.
I get it is just an example, but I was just pointing out that an example that outputs all the actual words of the file (as I thought was intended) would be better.
Thanks for your time and patience, though :-)