[英]For Java, if I want to do an if statement to make sure the input only takes in one character, how should I proceed?
I am trying to do a while loop to get user input and make sure what they put is a character only, so if they do ab, it will ask them to do another user input instead of taking the first letter they entered as an answer.我正在尝试做一个while循环来获取用户输入并确保他们输入的只是一个字符,所以如果他们做ab,它会要求他们做另一个用户输入,而不是把他们输入的第一个字母作为答案。 Can I do this with a try catch such as the one below?我可以使用如下所示的 try catch 来执行此操作吗? It is not working right now and I am not sure why.它现在不工作,我不知道为什么。
Thanks for your help!谢谢你的帮助!
boolean single = true;
while(single) {
try {
if(letter.length()==1) {
break;
} else {
System.out.println("Please enter a single character only!");
}
} catch (Exception e) {
System.out.println("Please enter a single character only!");
}
}
I am trying to do a while loop to get user input and make sure what they put is a character only, so if they do ab, it will ask them to do another user input instead of taking the first letter they entered as an answer.我正在尝试做一个while循环来获取用户输入并确保他们输入的只是一个字符,所以如果他们做ab,它会要求他们做另一个用户输入,而不是把他们输入的第一个字母作为答案。 Can I do this with a try catch such as the one below?我可以使用如下所示的 try catch 来执行此操作吗? It is not working right now and I am not sure why.它现在不工作,我不知道为什么。
Thanks for your help!谢谢你的帮助!
boolean single = true;
while(single) {
try {
if(letter.length()==1) {
break;
} else {
System.out.println("Please enter a single character only!");
}
} catch (Exception e) {
System.out.println("Please enter a single character only!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.