验证java中的整数和整数范围

时间:2014-06-30 01:54:56

标签: java

我已经在这个简单的问题上工作了好几个小时而没有到达任何地方。我试图验证输入到我的程序中的数字是在1到12之间。我已经尝试了几种循环,但得到了各种错误和问题,我在顶部的评论中详细说明了这些错误和问题。示例代码:

//This gives me an error saying that the local variable deptMonth may not have
//been initialized

boolean monthCorrect;
int deptMonth;
Scanner input = new Scanner(System.in); 

    do
    {
        System.out.print("Please input the month (1-12): ");
        if (input.hasNextInt())
        {
            if ((input.nextInt()) <= 12 && (input.nextInt()) >=1)
            {
                deptMonth = input.nextInt();
                monthCorrect = true;
            }
            else
            {
                System.out.println("I don't understand try again.");
                monthCorrect = false;
                input.next();
            }
        }
        else
        {
            System.out.println("I don't understand try again.");
            monthCorrect = false;
            input.next();
        }

    }while (!(monthCorrect));

有没有更简单,更正确的方法呢?

谢谢。

2 个答案:

答案 0 :(得分:0)

您反复调用方法nextInt。这不会占用多个输入令牌吗?试试这个:只调用一次nextInt并将其分配给变量,我们称之为foo。然后测试foo以查看它是否在正确的范围内,如果是,请将foo分配给deptMonth

答案 1 :(得分:-1)

像罗伯特说的那样,你需要分配     input.nextInt()
到do循环内部的变量。多次调用此方法会导致您必须多次输入值。因此,为了使您的代码能够正常工作,它应该更像这样:

boolean monthCorrect;
int deptMonth;
Scanner input = new Scanner(System.in); 

do
{
    System.out.print("Please input the month (1-12): ");
    if (input.hasNextInt())
    {
        int tmp = input.nextInt();
        if ((tmp) <= 12 && (tmp) >=1)
        {
            deptMonth = tmp;
            monthCorrect = true;
        }
        else
        {
            System.out.println("I don't understand try again.");
            monthCorrect = false;
        }
    }
    else
    {
        System.out.println("I don't understand try again.");
        monthCorrect = false;
    }

}while (!(monthCorrect));

此外,我不知道您是否继续输入,但最好在完成后关闭扫描仪,以防止内存问题等。

所以,

if ((tmp) <= 12 && (tmp) >=1)
        {
            deptMonth = tmp;
            monthCorrect = true;
        }

应该是这样的:

if ((tmp) <= 12 && (tmp) >=1)
        {
            deptMonth = tmp;
            monthCorrect = true;
            input.close();//This keeps everything tidy! Also eclipse should give you a warning message if you forget to include it!
        }