简体   繁体   中英

Java - !String.equals(“abc”) returning TRUE when it should be FALSE

I am working on this problem for school (please ignore any other errors you may see, I'm still working through it). I am getting stuck on my while loop.

I'm working to add in a check for if the user doesn't input a c or f to re-ask them until they input one of those two letters.

However, as I debug it I am finding the function is ignoring the ! in my statement and returning TRUE when the value for units is c .

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

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

Just go through it and think about it. The above is always true, regardless of what units holds.

Let's say it holds "c" .

let's fill it in:

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

I'm pretty sure you meant !units.equals("c") && !units.equals("f") instead, or maybe !(units.equals("c") || units.equals("f")) which boils down to the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM