简体   繁体   中英

Why won't the scanner prompt me for an input?

I have this method:

public String scanInput()
{
    String input = "";
    Scanner skanner = new Scanner(System.in);
    while(skanner.hasNextLine()){
        input = skanner.nextLine();
    }
    skanner.close();
    return input;
}

The first time this method is run, the program stops, and I'm prompted for an input in the console before it can proceed. However, the second time the method is run, it flashes by without pausing, and my program is stuck in an endless loop.

What line in this method makes the program pause, and why does it only pause the first time?

You're closing the scanner near the end of the method. That closes the stream it's working on - System.in in this case. That means next time you call the method, the stream is still closed, so there are no lines.

You should set up one Scanner , and pass that into the method (or have it as state within your class).

The reason your program flashes by without pausing the second time it is run is because System.in is closed - closing a Scanner object will close the underlying stream.

As Jon has mentioned, the scanner should really be set up outside this function, once, and passed into the method.

To answer your second question - the line that causes the program to pause is the .nextLine() call. nextLine() is what is known as a "blocking function".

Right now, your code only works one time because System.in is essentially the console. You cannot "open" System.in . A closed stream cannot be reopened.

Yes, you're making a new Scanner everytime you call the function - but making a Scanner object doesn't make a new stream - the Scanner object only takes in a stream as a parameter.

skanner.hasNextLine()在这种情况下返回false,因为它不会从文件/网站等读取。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM