使用while循环java检查来自扫描程序的输入是否为int [英] checking if input from scanner is int with while loop java

查看:29
本文介绍了使用while循环java检查来自扫描程序的输入是否为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上希望下面的while循环检查输入是否为整数.它不能包含小数,因为它指向一个数组.如果输入的值为十进制,则应再次提示用户.问题是在使用此代码开始while循环之前,我得到了两个提示.有什么想法吗?

I basically want the following while loop to check if the input is an integer. It cannot contain decimals because it is pointing to an array. If the value entered is a decimal it should prompt the user again. Problem is I get two prompts before the while loop starts with this code. Any ideas?

      System.out.print("Enter month (valid values are from 1 to 12): ");
    Scanner monthScan = new Scanner(System.in);
    int monthInput = monthScan.nextInt();
    // If the month input is below 1 or greater than 12, prompt for another value
    while(monthInput<1 || monthInput>12 || !monthScan.hasNextInt())
    {
        System.out.print("Invalid value! Enter month (valid values are from 1 to 12): ");
        monthInput = new Scanner(System.in).nextInt();
    }

谢谢

当前输出显示以下内容:

The current output gives the following:

Enter month (valid values are from 1 to 12): 2
2

请注意,即使这是一个有效值,我也必须两次输入两次.

Notice how I had to enter 2 twice even though it is a valid value.

推荐答案

对程序进行少量修改即可解决问题

A small modification to your program solves the problem

 System.out.print("Enter month (valid values are from 1 to 12): ");
        Scanner monthScan = new Scanner(System.in);
       int monthInput = monthScan.nextInt();
        // If the month input is below 1 or greater than 12, prompt for another value
        while((monthInput<1 || monthInput>12) )
        {
            System.out.print("Invalid value! Enter month (valid values are from 1 to 12): ");

            monthInput = monthScan.nextInt();
        }
        System.out.println("I am here");

输出:

Enter month (valid values are from 1 to 12): -5
Invalid value! Enter month (valid values are from 1 to 12): -5
Invalid value! Enter month (valid values are from 1 to 12): -2
Invalid value! Enter month (valid values are from 1 to 12): 5
I am here

希望这对您有所帮助.

这篇关于使用while循环java检查来自扫描程序的输入是否为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆