我不确定如何验证用户是否只输入一个字符进行输入。我知道我进行长度检查的内容根本不正确。我只是用它作为填充物。请帮忙。我尝试了许多不同的方法,并搜索了这个网站和其他网站几天,以找到答案。
final char SIZE = 10;
char [] letter = new char [SIZE];
// initiallizing input device
Scanner scan = new Scanner(System.in);
for (char index = 0; index < SIZE;)
{
System.out.println ("Please enter Letter #" + (index + 1));// gets letter from user
while ((!scan.hasNext("[A-Za-z]+")) || (!scan.hasNext(length(1)))){
if(!scan.hasNext(length (1))){
System.out.println ("Please only enter one Letter at a time: ");
letter [index] = scan.next().charAt(0); // accepts first character entered by user
}
if(!scan.hasNext("[A-Za-z]+")){
System.out.println ("Please enter a valid Letter: ");
letter [index] = scan.next().charAt(0); // accepts first character entered by user
}
else if((scan.hasNext("[A-Za-z]+")) && (scan.next(length(1)))){// makes sure letter entered is a letter
letter [index] = scan.next().charAt(0); // accepts first character entered by user
index++;// increases index if proper letter entered
}
}
}
for (char index = 0; index < SIZE; index++)
{
System.out.println ("Letter #" + (index + 1) + ": " + letter [index]);// prints characters entered by user in order
}
有很多方法可以做到这一点。一种方式是A.K.发布的内容。一种方式如下:
for (char index = 0; index < SIZE;)
{
String temp = scan.nextLine();
if (temp.length() != 1)
{
// This means their input was too big
}
else
{
// This means their input was one character
}
}
您还可以使用 scan.next().charAt(0);
此行代码将仅从控制台获取一个字符作为输入。
如果您有任何问题或此答案不是您想要的,请在下面发表评论,我很乐意为您提供帮助。
一种解决方案是这样的:
Scanner sc = new Scanner(System.in);
System.out.println("Enter char");
String in = sc.next();
while(in.length()!=1){
System.out.println("Enter only a single char");
in = sc.next();
}
// Print the read value
System.out.println("Your char is = " + in);
如果您还想检查它是否是字母而不是数字,只需在 while 循环中添加一个检查即可。
输入仅在用户按 Enter 后放在缓冲区上,因此实际上它始终是一次一行。您应该始终将代码与现实保持一致,因此请始终按行读取用户输入。
此实用程序方法可能有用:
private static String read(Scanner scanner, String message, String regex) {
System.out.println(message);
String result = "";
while (true) {
result = scanner.nextLine();
if (result.matches(regex)) {
break;
}
System.out.println("Invalid input. " + message);
}
}
你可以这样称呼它:
String letter = read(scan, "Please enter Letter #" + (index + 1)", "[A-Za-z]");
在只输入一个字母之前,read()
方法不会返回,它将返回该字母。