[英]Problems with java validation for user input
我知道有很多关于 Java 输入验证的问题,但无论我阅读什么,我似乎都无法让它发挥作用。 我希望用户将出生日期输入为 (MM DD YYYY)。 我想验证一下
我第一次尝试使用 int 变量,但似乎无法将hasNextInt()
与数字长度和范围结合起来。 然后我看到一个帖子说要做 String 变量,然后使用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 块的情况下进行此验证,因为它们看起来太大了。 谢谢!
如果你想使用正则表达式,你可以试试这个
while(!(Pattern.matches("(0)[1-9]{1}|(1)[0-2]",month)))
{
System.out.println("Enter again \n");
month=input.next();
}
要使此代码正常工作,您需要在程序开头使用它来包含正则表达式包
import java.util.regex.*;
我们的正则表达式分为两部分“ (0)[1-9]{1} ”,这将首先确保字符串包含“0”,然后是 1-9 之间的任何数字。 而“ {1} ”将确保它只出现一次。
如果需要,类似地编写日和年的代码。
使用DateTimeFormatter是这样的:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM dd yyyy");
try {
LocalDate date = LocalDate.parse(input, formatter);
} catch (DateTimeParseException e) {
// Thrown if text could not be parsed in the specified format
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.