简体   繁体   English

如何比较java中的单个字符

[英]how to compare single char in java

I want to input character from user.If user inputs character 'Y' then continue else exit from application.我想从用户输入字符。如果用户输入字符“Y”,则继续否则退出应用程序。 For looping I am using do-while.对于循环,我使用 do-while。 Condition for application is used in while block.应用条件在 while 块中使用。 But it's not working.Whatever user inputs application doesn't exit and continue.但它不起作用。无论用户输入什么,应用程序都不会退出并继续。

char choice='\u0000';
do
{
    System.out.println("Enter Y to continue or N to exit");
    choice=(char)System.in.read();
}
while(choice!='N');
choice = (char) System.in.read(); 

(casting a byte from system encoding to UTF-16) will only work if the characters have identical values in both encodings; (将一个字节从系统编码转换为 UTF-16)仅当字符在两种编码中具有相同的值时才有效; this will usually only work for a very small range of characters.这通常只适用于很小范围的字符。 Using Scanner is more reliable.使用扫描仪更可靠。

I updated your query, with Scanner class for reading character.我更新了您的查询,使用 Scanner 类读取字符。

Scanner reader = new Scanner(System.in);
char choice='\u0000';
do
{
    System.out.println("Enter Y to continue or N to exit");
    choice = reader.next().charAt(0);
}
while(choice!='N' && choice != 'n');

I think it would be easyer if you do it like this:我认为如果你这样做会更容易:

char choice='\u0000';
System.out.println("Enter Y to continue or N to exit");
Scanner reader = new Scanner(System.in);
while(choice!='N' && choice!='Y' && choice!='n' && choice!='y') {
    choice = reader.nextLine().charAt(0);
}
reader.close();

After that you can show if he typed N or Y and continue with your code之后你可以显示他是否输入了 N 或 Y 并继续你的代码

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

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