麻烦我的条件声明

时间:2014-06-09 01:16:11

标签: java while-loop conditional-statements

我正在尝试通过三个数字来检查用户。我似乎无法解决这个问题,我想确保用户只选择这3个数字中的一个。

System.out.println("How big do you want your pizza? Enter a size of: 10, 12, or 14 inches.");
size = scan.nextInt();
while( size != 10 )  <=====(**PROBLEM**)
{
    System.out.println("That is not a valid size. Choose again.");
    size = scan.nextInt();
}

3 个答案:

答案 0 :(得分:4)

您希望继续循环直到获得10,12或14,因此请使用

while (size != 10 && size != 12 && size != 14) {
    ...
}

its equivalent

while (!(size == 10 || size == 12 || size == 14)) {
    ...
}

答案 1 :(得分:1)

int[] allowedSize = {10, 12, 14};

if (in_array(size, allowedSize) == false)
{
   // Size is not good
}


public static boolean in_array(Object needle, Object[] haystack) {
        return (Arrays.binarySearch(haystack, needle) >= 0);
    }

答案 2 :(得分:1)

在java中,您可以使用&#39;&amp;&amp;&#39;就像你会&#39;和&#39; 在你的情况下,你可以这样做:

size = scan.nextInt();
while( size != 10 && size != 12 && size != 13 )  <=====(**PROBLEM**)
{
    System.out.println("That is not a valid size. Choose again.");
    size = scan.nextInt();
}