【问题标题】:Java - !String.equals("abc") returning TRUE when it should be FALSEJava - !String.equals("abc") 在应该为 FALSE 时返回 TRUE
【发布时间】:2020-09-15 16:20:44
【问题描述】:

我正在为学校解决这个问题(请忽略您可能看到的任何其他错误,我仍在解决它)。我陷入了我的 while 循环。

我正在努力检查用户是否没有输入 cf 以重新询问他们,直到他们输入这两个字母之一。

但是,当我调试它时,我发现该函数忽略了我的语句中的!,并在units 的值为c 时返回TRUE

public class TempConvert {
    
    // converts from fahrenheit to celsius
    static int convToCelsius(int tempF) {
        int tempC = (tempF - 32) * 5 / 9;
        return tempC;
    }

    // converts from celsius to fahrenheit
    static int convToFahrenheit(int tempC){
        int tempF = (tempC * 9 / 5) + 32;
        return tempF;
    }

    public static void main(String[] args){

        int temp;       // user specified temp
        int convTemp;   // var for converted temp
        String units;   // user specified unit

        System.out.println("This program converts Temperatures from Fahrenheit to Celsius and vice versa.");
        System.out.print("Please enter your temperature: ");
        temp = TextIO.getlnInt();
        System.out.print("Please enter the units (F/C):");
        units = TextIO.getlnWord().toLowerCase();

        while (!units.equals("c") || !units.equals("f")){
            System.out.print("Please enter F for Fahrenheit or C for Celsius: ");
            units = TextIO.getlnWord();
        }

        if (units.equals("c")){
            convTemp = convToFahrenheit(temp);
            System.out.printf("A temperature of %d degrees Fahrenheit is equivalent to %d degrees Celsius", temp, convTemp);
        }

        else if (units.equals("f")){
            convTemp = convToCelsius(temp);
            System.out.printf("A temperature of %d degrees Celsius is equivalent to %d degrees Fahrenheit", temp, convTemp);
        }

    } // end main

} // end class

【问题讨论】:

    标签: java string inequality


    【解决方案1】:

    !units.equals("c") || !units.equals("f")

    只是通过它并考虑它。无论units 持有什么,上述情况总是正确。

    假设它拥有"c"

    让我们填写:

    !units.equals("c") || !units.equals("f")
    !true || !false
    false || true
    true
    

    我很确定您的意思是 !units.equals("c") && !units.equals("f"),或者可能是 !(units.equals("c") || units.equals("f")),归结为同一件事。

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多