【发布时间】:2021-05-04 04:20:28
【问题描述】:
我目前正在为我的 Java 类处理一个问题,我正在做 do-while 循环,当我的 while 条件与用户输入的字符串有关时我遇到了麻烦。代码可以编译,但无论我输入什么,它都会使 while 条件失败并再次执行循环。这甚至发生在我硬编码 unit 的值时。
我尝试在网上查找解决方案,但我能找到的每个示例都使用用户输入的 int 值而不是字符串
public class unit {
public static void main (String[] args) {
String prompt = "Please enter your preferred unit of mass (kg, lb, g or oz): ";
System.out.println(preferredUnit(prompt));
}
public static String preferredUnit(String prompt) {
Scanner sc = new Scanner(System.in);
String unit = "";
do{
if (!unit.equals("")) {
System.out.println("Sorry but " + unit + " is not a valid unit type");
}
System.out.println(prompt);
unit = sc.nextLine();
} while(!unit.equals("kg") || !unit.equals("lb") || !unit.equals("g") || !unit.equals("oz") );
return "Unit of mass: " + unit;
}
}
【问题讨论】:
-
while 循环条件中的问题。
-
它总是返回真。因为当您输入任何内容时,它会检查 !unit.equals("kg") 是否返回 true。所以它是 OR 运算符。其中一个是真正的意思是再次运行时
-
使用 && 运算符代替 ||。
标签: java