在 while 循环中比较字符串

Comparing Strings in while loop

我正在尝试编写一个代码,将用户字符串与字符串 '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){

}

那也不行

所以我尝试使用有效的布尔值,但如果用户不输入一个字母,另一个字母就会变为 false 并激活 while 循环

您必须对字符串使用以下内容:

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

不要使用 == 比较字符串,使用等号。

也是测试

m == false || f == false

不是您想要的,它的计算结果始终为真:

  • 如果您输入 'M',则 (f == false) 计算结果为真。

  • 如果您输入 'F',则 (m == false) 计算结果为真。

  • 如果输入'X',则(m == false)为真,(f == false)为真。

逻辑或表示如果 A 为真或 B 为真,则 A OR B 为真。

应该是(!m && !f)也就是"your input is not 'M' and your input is not 'F'"。

或者等价地写成!(m || f):"it is not the case that the input is either 'M' or 'F'".

你应该比较字符串

string1.equals(string2)

没有

string1 == string2

除了将运算符从 == 更改为 .equals() 之外,您还需要决定是否需要在测试验证之前将它们都设置为 true。我会将它们设置为 false,这样您就不需要在验证语句中更改 boolean mboolean 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;
    }

阅读起来更快更容易。

尝试将布尔变量设置为 False。

布尔值 m = false; 布尔 f = false;

这应该会给你想要的结果。