The definition of hasNext() is "Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input."
When I put standardInput.hasNext() in for-loop, the program runs toward infinity. But if i Put it in while-loop it does not run to infinity. Where is the differenc between these two programs and why one of them work and another not?
for-loop:
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);
}
}
}
while-loop:
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 ".");
}
}
I read the definition, but still cannot understand why one program works but another not
CodePudding user response:
TLDR: The two programs behave differently because their code is not equivalant.
In the while loop, you get the next token by calling standardInput.nextDouble()
. This changes the result of standardInput.hasNext()
on each iteration.
On the other hand, the for loop version never gets the next token, so the value returned by hasNext()
never changes.
CodePudding user response:
In for...loop
you do not read standardInput
to get it, but you check it in the codition; you do it in the while...loop
.
To fix it you should add scanner reading inside the loop;
for(int i = 0; standardInput.hasNext(); i ){
String str = standardInput.next(); // add reading
System.out.print(i);
}
CodePudding user response:
It's because these lines of code only check if there is to be read but not actually reading the file, thus, not advancing the file pointer.
for(int i = 0; standardInput.hasNext(); i ){
System.out.print(i);
}
While these lines of code actually read a type double using the Scanner object.
while(standardInput.hasNext()) {
double nextNumber = standardInput.nextDouble();
sum = nextNumber;
}