简体   繁体   中英

(Java) Comparing char values using relational operators in nested if statements

I am a newcomer here and just ran into this issue in a textbook. I'm currently learning about nested if statements and I can't seem to get this to work (even though the textbook says it is correct). It is a guess a letter game, but every time the answer is deemed "incorrect" the "nested if statement" ( if (ch < answer ) System.out.println("Too low!"); ) is never read even if you enter a letter alphabetically lower than 'K'. The printout will always read "Too High!". Any insight on this would be much appreciated.

class GuessLetter {
    public static void main(String args[])
        throws java.io.IOException {

        char ch, answer = 'K';

        System.out.println("I'm thinking of a letter between A and Z.\nCan you guess it?");

        ch = (char) System.in.read();

        if (ch == answer) { 
            System.out.println("Correct!");
        } else{
            System.out.println("Incorrect!");

            **if (ch < answer ){
                System.out.println("Too low!");**
            } else {
                System.out.println("Too high!");
            }
        }   
    }
}

It works, you are probably entering "k" instead of a capital letter "K". If you enter a letter "bigger" then "K", it will print "Incorrect! Too high!".

(The same holds for letters that are too low, if I enter "J" it will say it is too low).

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