gpt4 book ai didi

java - 如何从 Java 中获取用户的单个字符输入?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:51:03 26 4
gpt4 key购买 nike

在下面的示例中,我尝试接受来自用户的单个字符输入,但是在运行程序时,我执行了多次 do..while 循环。请在下面查看程序的结果。

如果有人能帮我解答,如何解决这个问题?

import java.io.*;



public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {



char c;
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DataInputStream in =new DataInputStream(System.in);

// Asking the user what to do with the application
do{

System.out.println("Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' ");

byte b = in.readByte();
c = (char) b;
c = Character.toUpperCase(c);

if (c=='Y'){
System.out.println(c);
}
else if (c=='N') {
System.out.println(c);
}
else if (c=='E'){
System.out.println(c);
}
else{
System.out.println("Incorrect Entry, try again: "+c);
}

}while (c!='E');

}

}

输出

init:
deps-jar:
compile:
run:
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
asdfgaf
Incorrect Entry, try again: A
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: S
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: D
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: F
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: G
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: A
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: F
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again:

Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'

最佳答案

使用 DataInputStream 可能不是处理您的情况的最佳方式。

DataInputStream 缓冲您键入的输入,这就是为什么您会收到不需要的带有循环的冗长消息。

尝试改用扫描仪。这是扫描仪的示例:

Scanner objScanner = new Scanner(System.in);
char c = objScanner.next().charAt(0);
System.out.println(c);

关于java - 如何从 Java 中获取用户的单个字符输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14871384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com