while (scanner.hasNext()) loop not working twice?

2019-08-20 04:37发布

问题:

I have made a program which is like a vending machine!

My code is similar to:

public static void main (String [] args) {
    Scanner sc = new Scanner (System.in);
    while(sc.hasNext()) {
        String string = sc.next();

        sum = generateSum(sum)
        .....
    }
}

public static int generateSum(int sum) {
    Scanner sc = new Scanner (System.in);
    while (sc.hasNext()) {
        ....
    }

    return sum;
}

Sorry for simplifying my code, but the normal one is very long! However, the problem is that I use while (sc.hasNext()) loop twice. Basically I want to continue my main method until the input from the user is TERMINATE, but my program terminates after running once.

I figured that if I take out my generateSum method, then the loop in my main method works fine so i guess it has to be something to do with have the while (sc.hasNext()) loop twice.

Any ideas how I can fix the problem?

回答1:

The hasNext() method is going to block until you hit the end of file marker on System.in because it doesn't know if there's more input until it reads a full buffers worth or hits end of file (which you can signal with Control-Z on windows and Control-D on unix). At that point System.in is at the EOF mark and there's no way to re-open it from your code.

If you need to process multiple streams of data from System.in you are going to have to use some sort of sentinel value (such as the word END) to mark the end of one input stream and the beginning of another.



回答2:

I'm quite sure that if you consume the input being scanned with sc.next() the state changes and hasNext() returns accordingly.The problem may be there.



回答3:

The hasNext() method can be called as much as you want. But if in the inner loop you are calling the next() method, then that can eat the values from your outer loop.

So the inner loop most probably breaks after hasNext() is false and thus the outer loop also finishes.