如何将int范围分配给if语句中的输入

时间:2014-06-10 02:28:37

标签: java if-statement int range

我在搜索最后一小时后如何实现这个问题时遇到了麻烦:

    if (age < 16)
    {
        System.out.println ("You can't drive " + name);
    }
    else if (age == 16-17)
    {
        System.out.println ("You can drive but you can't vote " + name);
    }
    else if (age == 18-24)
    {
        System.out.println ("You can vote but you can't rent a car " + name);
    }
    else
    {
        System.out.println ("You can do anything you wish " + name);
    }

我只是不确定如何使输入值等于一组或一组数字。我一直在研究最后一小时,我似乎无法找到一种简单的方法来实现一系列数字并将它们分配给if语句中的某些内容。这段代码实际上有效,但是如果任何int是&gt; 16它默认为else语句。

4 个答案:

答案 0 :(得分:4)

现在您正在if age == (18 - 24)转换为age == -6

如果您想检查范围,只需使用边界:if age >= 18 && age <= 24

答案 1 :(得分:0)

您的问题是您正在16-1718-24进行数学减法。您应该使用age == 16 || age == 17age >= 18 && age <= 24。就个人而言,我会尝试使用switch声明。

答案 2 :(得分:0)

  if (age < 16)
    {
        System.out.println ("You can't drive " + name);
    }

    else if (age == 16 || age==17)
    {
        System.out.println ("You can drive but you can't vote " + name);
    }

    else if (age >=18 && age<=24)
    {
        System.out.println ("You can vote but you can't rent a car " + name);
    }

    else
    {
        System.out.println ("You can do anything you wish " + name);
    }

答案 3 :(得分:0)

移动到函数

会更好
public static boolean isBetween(int x, int lower, int upper) {
  return x >= lower && x <= upper;
}

if (isBetween(age, 0, 15)) {
  System.out.println ("You can't drive " + name);
} 
if (isBetween(num, 16, 17)) {
  System.out.println ("You can drive but you can't vote " + name);
}