【发布时间】:2023-03-25 12:59:02
【问题描述】:
问题在于,while 循环中的第一个条件即使为真,也根本不会被执行。如果我从 while 循环中删除逻辑 OR 并只写第一个条件(selection.compareToIgnoreCase("O") >0)它工作正常。但是如果逻辑或有两个条件,就不行了。
我尝试过使用equals(),我也尝试过使用否定逻辑
while(!selection.equals("O") || !selection.equals("E"))。第二个条件很好,但第一个根本不起作用。
public class OddsOrEvens {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
System.out.println("Let’s play a game called \"Odds and Evens\"");
System.out.println("Whats your name ? ");
String name = sc.nextLine();
System.out.println("Hi "+ name +", which do you choose? (O)dds or (E)vens?");
String selection = sc.nextLine();
System.out.println("selection: " + selection);
while (selection.compareToIgnoreCase("O") >0 || selection.compareToIgnoreCase("E") >0){
System.out.println("Please enter the correct choice. Select 'O' for odds or 'E' for evens");
selection = sc.next();
}
if(selection.equalsIgnoreCase("O")){
System.out.println(name + " has picked Odds! The computer will be evens.");
}else if (selection.equalsIgnoreCase("E")){
System.out.println(name + " has picked Evens! The computer will be Odds.");
}
}
}
【问题讨论】:
-
你真的应该写出你的条件的真值表。
-
你试过调试吗?
-
selection.compareToIgnoreCase("O") >0正在检查选择是否大于"O". Tryselection.compareToIgnoreCase("O") == 0`。 -
是的,我尝试过调试,变量(Selection)中的值总是如预期的那样,但循环不能正常工作。
-
@oldCurmdgeon 如果我将其更改为 == 那么它将进入无限循环。
标签: java while-loop conditional logical-operators