简体   繁体   English

比较Java中的char变量

[英]Comparing char variables in java

I would compare a char, but it actually doesn't work: 我会比较一个字符,但实际上不起作用:

//...
System.out.print("PROCEED? (Y/N):\t");
line = in.nextLine();
ch = line.charAt(0);

while (ch != 'y' || ch != 'n' || ch != 'Y' || ch != 'N'){
    System.out.print("NON-VALID INPUT. TYPE Y-N:\t");

    line = in.nextLine();
    ch = line.charAt(0);
}
//...

On my terminal, as I press y or n , the result is: 在我的终端上,按yn ,结果是:

PROCEED? (Y/N): y
NON-VALID INPUT. TYPE Y-N:  y
NON-VALID INPUT. TYPE Y-N:  Y
NON-VALID INPUT. TYPE Y-N:  n
NON-VALID INPUT. TYPE Y-N:  r
NON-VALID INPUT. TYPE Y-N:  d
...

Your condition is wrong. 您的情况不对。 It should be : 它应该是 :

while(ch!='y' && ch!='n' && ch!='Y' && ch!='N')

since the loop should continue as long as the input character is different than all 4 acceptable inputs. 因为只要输入字符与所有 4个可接受的输入都不同,循环就应该继续。

You need to use && instead of || 您需要使用&&代替|| in your while loop. 在您的while循环中。

The condition is wrong. 条件是错误的。 You have to put the "and" condition (&&), for only enter to that condition if the user type either except ('Y', 'y', 'N', 'n'). 您必须输入“和”条件(&&),仅当用户键入以下任意一种情况(“ Y”,“ y”,“ N”,“ n”)时才输入该条件。 The code would be as follows: 代码如下:

    System.out.print("PROCEED? (Y/N):\t");
    Scanner in = new Scanner(System.in);
    String line=in.nextLine();
    Character ch=line.charAt(0);

    while(ch!='y' && ch!='n' && ch!='Y' && ch!='N'){
        System.out.print("NON-VALID INPUT. TYPE Y-N:\t");

        line=in.nextLine();
        ch=line.charAt(0);
    }

Hope this can help you. 希望这可以帮到你。

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

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