无论如何,看看我的用户输入是否在一定范围内?

时间:2014-04-12 03:28:01

标签: java if-statement range user-input

我正在接受用户的一些输入,我需要确保输入介于200-800之间。对于我的所有变量,我应该只使用if语句还是有快捷方式?

System.out.print("SAT Math: ");
int satMath = kb.nextInt();
System.out.print("SAT Reading: ");
int satReading = kb.nextInt();
System.out.print("SAT Writing: ");
int satWriting = kb.nextInt();
//If score is out of range.
if (((satMath < 200 || satMath > 800) || (satReading < 200 || satReading > 800) || (satWriting < 200 || satWriting > 800)))
{
   System.out.println("Did not enter a value in range!");
   System.exit(-1);
}

3 个答案:

答案 0 :(得分:2)

你的逻辑是正确的,但你的实现有点奇怪。你基本上想要为每个值做同样的事情,所以为什么不在输入值时立即检查它,而不是在最后输入,如下所示:

class SAT
{
    private static final Scanner sc = new Scanner(System.in);

    private static int getInt(final String subject)
    {
        System.out.println("SAT " + subject + ": ");
        final int value = sc.nextInt();
        if(value < 200 || value > 800)
        {
            System.out.println("Did not enter a value in range! (200-800)");
            System.exit(-1);
        }
        return value;
    }

    public static void main(String[] args)
    {
        int maths = getInt("Math");
        int reading = getInt("Reading");
        int writing = getInt("Writing");
    }
}

答案 1 :(得分:1)

使用单独的if语句,如果输入超出范围,则显示哪个输入超出范围,以便用户下次输入正确的输入。没有捷径对不起!

答案 2 :(得分:0)

有了这样的重复代码,我通常会重构它,就像这样:

// reusable in-range method
private static boolean between(int value, int low, int high) {
    return value >= low && value <= high;
}

// reusable version for this task, because they all share the same range
private static boolean isOK(int value) {
    return between(value, 200, 800);
}

然后

if (!isOK(satMath) || !isOK(satReading) || !isOK(satWriting)) {
    System.out.println("Did not enter a value in range!");
    System.exit(-1);
}