简体   繁体   English

(Java)在嵌套if语句中使用关系运算符比较char值

[英](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). 我目前正在学习有关嵌套if语句的信息,而且似乎无法使它正常工作(即使教科书说这是正确的)。 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'. 这是一个猜谜游戏,但是每次答案被认为“不正确”时,即使“ 即使嵌套”语句( if(ch <answer)System.out.println(“ Too low!”); )也不会被读取您输入的字母字母顺序低于“ 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". 它有效,您可能输入的是“ k”而不是大写字母“ K”。 If you enter a letter "bigger" then "K", it will print "Incorrect! Too high!". 如果输入字母“更大”,然后输入“ K”,它将打印“错误!太高!”。

(The same holds for letters that are too low, if I enter "J" it will say it is too low). (对于太低的字母也是如此,如果我输入“ J”,它将表示它太低)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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