在Java中循环无穷

时间:2014-05-10 14:49:42

标签: java loops while-loop

int option=0;

while (option1!=1 || option1!=2){                   
    System.out.println("Give 1 for the first list which includes what we have in our exhibition");
    System.out.print("and 2 which we have not:"); // 2 print because i want to show at two different lines
    option1= Integer.parseInt(in.nextLine());} // when i give 1 or 2 as an option it doesn't goes out frome the loop

2 个答案:

答案 0 :(得分:3)

这是一个无限循环:

while(option1!=1 || option1!=2)

由于option1永远不能同时等于 1 2,所以这个条件将始终评估为true,循环将始终继续。你可能想要使用逻辑"和"运算符(&&)在您的比较中:

while(option1!=1 && option1!=2)

这样,如果option1等于这两个选项中的一个,循环将结束。

答案 1 :(得分:1)

您需要说option1!=1 && option1!=2,而不是option1!=1 || option1!=2

请记住格式化代码,使其可读。只需在每行前面添加四个空格即可。