can somebody explain, why does this loop run endlessly? I thought that the boolean **hasNext() ** is only true if there are no elements anymore. So when I type something in the loop runs like I typed something that goes endless too. And what are these nmbers? please explain
import java.util.Scanner;
public class Vocabulary {
public static void main(String[] args) {
Scanner standardInput = new Scanner(System.in);
for(int i = 0; standardInput.hasNext(); i ){
System.out.print(i);
}
}
}
I researched in Internet about hasNext(). I know what it makes and I know how the for-loop works. But I don´t know why hasNext in for-loop makes the programm run endlessly.
Edit:
On the other hand, this code works. Why does this code work?
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner standardInput = new Scanner(System.in);
double sum = 0;
while(standardInput.hasNext()) {
double nextNumber = standardInput.nextDouble();
sum = nextNumber;
}
System.out.println("The Sum is " sum ".");
}
}
CodePudding user response:
hasNext()
returns true
if there is something waiting on the Scanner standardInput
for being picked up. But you never pick it up, so it stays there and waits – endlessly, same as your loop.
CodePudding user response:
standardInput.hasNext()
is always true which is why you have an infinite loop.
hasNext()
only checks if there is another token in the scanner and never moves from the start. For example when putting in the string "StackOverflow", the next token is always "StackOverflow".
One problem with using hasNext()
in your case is that using Scanner halts the program and waits for an input, so it's always true so long as it has taken an input.
In this case, it looks like you're trying to iterate over the length of the scanner input and print the current character count each time - it might be better to assign the output of nextLine()
to a variable and iterate over that instead. See below for an example:
import java.util.Scanner;
class Vocabulary {
public static void main(String[] args) {
Scanner standardInput = new Scanner(System.in);
String input = standardInput.nextLine();
System.out.println("Scanner hasNext:" standardInput.hasNext()); // we can see that hasNext pauses our program
for (int i=0;i<input.length();i ) {
System.out.print(i " ");
}
}
}
The output looks like this:
StackOverflow
hasNext
Scanner hasNext:true
0 1 2 3 4 5 6 7 8 9 10 11 12