How do I close a scanner in java?

倾然丶 夕夏残阳落幕 提交于 2019-12-06 03:47:40

You should check if you have data to consume for Scanner using hasNextLine api which you could do like:

String string = "";
if (input_scanner.hasNextLine()) {
    string = input_scanner.nextLine();
}

Well, first I recommend you to use the API to understand the exceptions that Java shows you.

Read this for further information about NoSuchElementException:
http://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html

When you use scanner, stringTokenizer, iterators... you have to verify that you have more elements to read before you try read them. If you don't do that, you can get that type of exceptions.

private static String input(String Message){
    Scanner input_scanner = new Scanner(System.in);
    System.out.print("\n" + Message);
    if (input_scanner.hasNextLine()){
       String string = input_scanner.nextLine();
    }
    input_scanner.close();
    return string;

If you want to read more than one line, use while (input_scanner.hasNextLine())

Your mistake is about the keyboard input. Read this to understand if you are doing well that part: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine%28%29

PS: is recommended to close your scanner with input_scanner.close() when you have finished with it.

Scott Sosna

use try-with-resources to guarantee that your scanner closes regardless if any exceptions occur.

try (Scanner input_scanner = new Scanner(System.in)) {
   .
   .
   .
}

You can use this with anything that implements AutoCloseable, and it's much better than requiring a bunch of try-catch for exceptions thrown when closing.

Actually, since you are using Scanner for System.in, this means it is a blocking call that will hold until it receives the first input from the user. Being a local variable, you don't really need to close the scanner, and you definitely don't need a while loop for hasNextLine();

private static String input(String Message){
Scanner input_scanner = new Scanner(System.in);
System.out.print("\n" + Message);
String string = input_scanner.nextLine();
return string;

A scanning operation may block waiting for input. If no inputs are received then the scanner object does not having to read which makes the Exception to thrown since it does not find the element that need to be close. By verifying does the stream consist anything that could be read by scanning object will helps you in getting this kind of exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!