如何让用户使用 java 中的扫描仪按 Enter 键获取默认值?

2024-02-16

假设我想要以下提示:

“输入迭代次数(400):”

其中,用户可以输入一个整数,或者直接按 Enter 键获取默认值 400。

如何使用 Scanner 类在 Java 中实现默认值?

public static void main(String args)
{
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the number of iterations (400): "); 
    input.nextInt();
}

正如你所看到的,我必须有“nextInt()”,我怎样才能做类似“nextInt或返回?”的事情,在这种情况下,如果它是返回,我将默认该值为400。

有人能指出我正确的方向吗?


我同意@pjp直接回答你关于如何调整扫描仪的问题(我给了他一个赞成票),但我的印象是,如果你只从标准输入中读取一个值,那么使用扫描仪有点矫枉过正。 Scanner 让我觉得你更想用它来读取一系列输入(如果这就是你正在做的事情,我很抱歉),但否则为什么不直接读取 stdin 呢?虽然现在我看它,它有点冗长;)

您可能还应该比我更好地处理 IOException...

public static void main(String[] args) throws IOException
{
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter the number of iterations (400): ");

    int iterations = 400;
    String userInput = input.readLine();

    //if the user entered non-whitespace characters then
    //actually parse their input
    if(!"".equals(userInput.trim()))
    {
        try
        {
            iterations = Integer.parseInt(userInput);
        }
        catch(NumberFormatException nfe)
        {
            //notify user their input sucks  ;)
        }
    }

    System.out.println("Iterations = " + iterations);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让用户使用 java 中的扫描仪按 Enter 键获取默认值? 的相关文章

随机推荐