Scanner无法在新实例上使用nextLine的问题

Scanner无法在新实例上使用nextLine的问题

本文介绍了Java Scanner无法在新实例上使用nextLine的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

package sandbox2;

import java.util.Scanner;

public class Sandbox2
{
    public static void main(String[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            String s = askForProperty("Enter value for " + i + ": ");
            System.out.println(i + " is: " + s);
        }

    }

    private static String askForProperty(String message)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.print(message);
        String s = keyboard.nextLine();
        keyboard.close();

        return s;
    }
}

当我运行上面的代码时,它会完美地返回第一个响应.当尝试请求第二个响应时,它返回:

When i run the above code, it returns the first response PERFECTLY. When it tries to ask for the second response, it returns:

java.util.NoSuchElementException: No line found

为什么会返回此错误?每次调用askForProperty方法时,扫描仪都是一个全新的实例!它与System.in作为输入流有关吗?

Why would it return this error? Each time the method askForProperty is called, the Scanner is a completely new instance! Does it have something to do with System.in as an input stream?

推荐答案

将扫描仪定义为类变量,然后在完成所有迭代后才将其关闭.在当前设置中,当您调用keyboard.close时,您还将关闭System.in,这使得以后无法使用.

Define your scanner as a class variable and then close it only after you are done with all iterations. In your current setup, when you call keyboard.close you are also closing System.in which makes it unusable later on.

package sandbox2;
import java.util.Scanner;

public class Sandbox2 {
    static Scanner keyboard = new Scanner(System.in); // One instance, available to all methods

    public static void main(String[] args)  {
        for (int i = 0; i < 5; i++) {
            String s = askForProperty("Enter value for " + i + ": ");
            System.out.println(i + " is: " + s);
        }
        keyboard.close(); //Only close after everything is done.
    }

    private static String askForProperty(String message) {
        System.out.print(message);
        String s = keyboard.nextLine();
        return s;
    }
}

这篇关于Java Scanner无法在新实例上使用nextLine的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:48