+ 1
Pals, Pls can anyone explain to me what's the use of the hasNext() method works in a program Like this. Scanner scan = new Scann
Pals, Pls can anyone explain to me what's the use of the hasNext() method works in a program Like this. Scanner scan = new Scanner(System.in); string grades; while( scan.hasNext() ) { grades = scan.next(); }
4 Réponses
+ 9
hasNext
Returns true if this scanner has another token in its input. [...]
Source: Language reference
https://docs.oracle.com/javase/9/docs/api/java/util/Scanner.html#hasNext--
Using this method as a condition for the while loop means, that the statements in the loop will be executed as long as there are more input tokens. You can use it to make sure to not read more tokens than were input (to avoid an exception).
0
hasNext() returns returns true if there is any further input. Specifically, it checks to see if the Scaner has reached the end of the input stream. When reading from System.in, it will always return true, since System.in remains open. To avoid an infinite loop, there should be some sort of exit condition. For instance,
while (!grades.equalsIgnoreCase(“exit”))
Alternatively, you could create an if statement within the loop which leads to a break statement when the exit string is entered.
0
https://code.sololearn.com/cZ5dqNvnGxNZ/?ref=app
Pls,
if you can,
open this code
and expalin to me while the compiler throws a noSuchElement excepion at line eleven.
0
It's SoloLearn bug, I left a comment on your code with more details.