[英]Java: Making a program keep prompting for user input when they enter nothing
I'm writing a program that asks for user input and keeps prompting the user for valid input if any of a few conditions aren't met. 我正在编写一个程序,要求用户输入内容,并在不满足以下任何条件的情况下不断提示用户输入有效的内容。 One such condition is that the input can't be an empty string. 这样的条件之一就是输入不能为空字符串。 (ie the user typing nothing and just pressing Enter). (即用户什么也不输入,仅按Enter键)。 How can I test for this? 我该如何测试? This is the code I have so far: (Note: the method isDateAcceptable isn't really relevant here because I want it to say "Number not acceptable." then re-prompt if the user enters ""). 这是我到目前为止的代码:(注意:方法isDateAcceptable在这里实际上并不相关,因为我希望它说“ Number not accept。”,然后在用户输入“”时再次提示)。 EDIT: I should add that with the current code, when a user enters an empty string the cursor just moves to the next line without ending the program. 编辑:我应该在当前代码中添加该代码,当用户输入一个空字符串时,光标将移至下一行而不结束程序。
public static String getNumOrDate(Scanner console){
System.out.print("Enter a number or a date mm/dd/yyyy (-1 to exit):");
String input = console.next();
while(!input.equals("-1")) {
if(input.isEmpty()){
System.out.println("Number not acceptable.");
getNumOrDate(console);
}
if (input.contains("/")) {
while (!isDateAcceptable(input)) {
System.out.println("Date not acceptable.");
getNumOrDate(console);
}
} else if (canBeParsed(input)) {
while (!isNumberAcceptable(input)) {
System.out.println("Number not acceptable.");
getNumOrDate(console);
}
}
}
System.out.println(isNumberAcceptable(input));
return input;
}
public static boolean canBeParsed(String input){
boolean parsable = true;
try{
Integer.parseInt(input);
}catch(NumberFormatException e){
parsable = false;
}
return parsable;
}
public static boolean isNumberAcceptable (String s){
boolean isAcceptable = true;
int numDigits = s.length();
if(s.isEmpty()&& s == null){
isAcceptable = false;
}
for(int i = 0; i < numDigits; i++){
if(!Character.isDigit(s.charAt(i))){
isAcceptable = false;
break;
}
}
if(isAcceptable){
int number = Integer.parseInt(s);
if((number < 1 && number != -1) || number > MAX_NUMBER){
isAcceptable = false;
}
}
return isAcceptable;
}
我建议您创建一个新的JFrame窗口并将一个输入字段和一个按钮拖到该窗口中。选择该按钮并在其上添加一个事件。然后您可以使用getText()方法生成字符串,并检查其是否为“”如果满足您的要求,则可以关闭Jframe(如果没有),它将仍然保持打开状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.