【发布时间】:2018-10-20 08:43:12
【问题描述】:
我知道有很多关于 Java 输入验证的问题,但无论我读到什么,我似乎都无法让它工作。我希望用户输入出生日期为(MM DD YYYY)。我想验证一下
- 用户只输入数字
- 他们输入了正确的位数,并且
- 数字在正确的范围内。
我第一次尝试使用 int 变量,但我似乎无法将 hasNextInt() 与数字长度和范围结合起来。然后我看到一个帖子说做字符串变量然后使用Integer.parseInt()。我认为如果我使用 (!month.matches("0[1-9]") || !month.matches("1[0-2]") 这会很好,因为它似乎满足了我所有的验证愿望。我在 while 语句中尝试了这个,但它陷入了无限循环。然后我尝试将该代码更改为 if...else 语句并用while(false) 语句包围它。但是,它现在会引发错误,而不是转到我的声明中说修复您的错误。这是我的代码目前的样子:
import java.util.Scanner; //use class Scanner for user input
public class BD {
private static Scanner input = new Scanner(System.in); //Create scanner
public static void main(String[] args){
//variables
String month;
int birthMonth;
String day;
int birthDay;
String year;
int birthYear;
boolean correct = false;
//prompt for info
System.out.print("Please enter your date of birth as 2 digit "+
"month, 2 digit day, & 4 digit year with spaces in-between"+
" (MM DD YYYY): ");
month = input.next();
//System.out.printf("%s%n", month); //test value is as expected
day = input.next();
year = input.next();
//validate month value
while (correct = false){
if(!month.matches("0[1-9]") || !month.matches("1[0-2]")){
System.out.println("Please enter birth month as "+
"a 2 digit number: ");
month = input.next();
//System.out.printf("%s%n", month);
}
else {
correct = true;
}
}
//turn strings into integers
birthMonth = Integer.parseInt(month);
birthDay = Integer.parseInt(day);
birthYear = Integer.parseInt(year);
//check values are correct
System.out.printf("%d%d%d", birthMonth, birthDay, birthYear);
}
}
任何帮助将不胜感激。我还想尝试在没有任何 try/catch 块的情况下进行此验证,因为它们看起来太笨重了。 谢谢!
【问题讨论】:
-
是否必须使用正则表达式?
-
使用适当的日期/时间 API 更好地完成日期/时间验证
-
@RoshanaPitigala 不,使用正则表达式不是强制性的。正是我在网上找到的似乎满足了我所有的验证要求。
标签: java validation input