这个问题在这里已有答案:
我正在尝试编写一个代码,将用户字符串与字符串'm'或'f'进行比较,如果用户的回答与两个字母都不匹配,则重复循环
public static void main(String[] args) {
String om = JOptionPane.showInputDialog("I will calculate the number of chocolate bar you should eat to maintain your weigth\n"
+ "Please enter letter 'M' if you are a Male\n"
+ "'F' if you are a Female");
JOptionPane.showMessageDialog(null, om.equalsIgnoreCase("m"));
// if i don't do this, it says the variables have not been initialized
boolean m = true;
boolean f = true;
if (om == "m"){
m = om.equalsIgnoreCase("m");
} else if ( om == "f"){
f = om.equalsIgnoreCase("f");
}
JOptionPane.showMessageDialog(null, "The m is: " + m);
JOptionPane.showMessageDialog(null, "The f is: " + f);
//if the user enters one variable the other variable becomes false, thus
// activating the while loop
while (m == false || f == false){
om = JOptionPane.showInputDialog("Please enter letter 'M' if you are a Male\n"
+ "'F' if you are a female");
}
/* i tried using '!=' to compare the string that doesn't work, i tired converting the strings to number to make it easier something like the code below:
int g = 2;
if (om = "m"){
g = 0
}
while (g != 0){
}
这也不起作用
所以我尝试使用boolean,但是如果用户没有输入一个字母,则另一个字母变为false并激活while循环
除了将运算符从==
更改为.equals()
之外,您还需要确定在测试验证之前是否将它们都设置为true
是必要的。我会将它们设置为false,因此您无需在验证语句中更改boolean m
和boolean f
的值。
boolean m = true;
boolean f = true;
if (om == "m"){
m = om.equalsIgnoreCase("m");
} else if (om == "f"){
f = om.equalsIgnoreCase("f");
}
可能
boolean m = false;
boolean f = false;
if (om.equalsIgnoreCase("m")){
m = true; //do not need to address the f because its already false.
} else if (om.equalsIgnoreCase("f")){
f = true;
}
它更快更容易阅读。
你应该比较字符串
string1.equals(string2)
没有
string1 == string2
您必须使用以下字符串:
if (om.equalsIgnoreCase("m") {
....
}
当您使用==
时,您正在比较值指向的参考,而.equals()
正在比较实际值。
例如:
String a = "foo";
String b = "foo";
a == b // This will return false because it's comparing the reference
a.equalsIgnoreCase(b) // This however will return true because it's comparing the value
不要使用==
来比较字符串,使用equals。
也是考验
m == false || f == false
不是你想要的,它总是评估为真:
(f == false)
评估为真。(m == false)
评估为true。(m == false)
为真,(f == false)
为真。逻辑OR表示如果A为真,或者B为真,则A OR B为真。
它应该是(!m && !f)
,这意味着“你的输入不是'M'而你的输入不是'F'”。
或者等价地,将其写为!(m || f)
:“输入不是'M'或'F'的情况。”
尝试将布尔变量设置为False。
boolean m = false;布尔值f = false;
这应该会给你想要的结果。