用户输入的java验证问题
我知道有很多关于Java输入验证的问题,但无论我读到什么,我似乎都无法让它起作用。我想让用户输入出生日期为(MM DD YYYY)。我想证实这一点用户输入的java验证问题,java,validation,input,Java,Validation,Input,我知道有很多关于Java输入验证的问题,但无论我读到什么,我似乎都无法让它起作用。我想让用户输入出生日期为(MM DD YYYY)。我想证实这一点 用户只能输入数字 他们做了正确的数字和数字 数字在正确的范围内 我的第一次尝试是使用int变量,但我似乎无法将hasnetint()与数字长度和范围相结合。然后,我看到一篇帖子说,先使用字符串变量,然后使用Integer.parseInt()。我认为如果我使用(!month.matches(“0[1-9]”)或{1}”将确保它只出现一次 同样,如果需
hasnetint()
与数字长度和范围相结合。然后,我看到一篇帖子说,先使用字符串变量,然后使用Integer.parseInt()
。我认为如果我使用(!month.matches(“0[1-9]”)或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块的情况下进行验证,因为这些块看起来太大了。
谢谢!请使用以下内容:
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
}
如果你想使用正则表达式,你可以试试这个
while(!(Pattern.matches("(0)[1-9]{1}|(1)[0-2]",month)))
{
System.out.println("Enter again \n");
month=input.next();
}
要使这段代码正常工作,您需要在程序开始时使用它来包含regex包
import java.util.regex.*;
我们的正则表达式分为两部分“(0)[1-9]{1}”,这将首先确保字符串包含“0”,然后是1-9之间的任何数字。“strong>{1}”将确保它只出现一次
同样,如果需要,请编写日期和年份的代码。是否必须使用正则表达式?日期/时间验证最好使用适当的日期/时间APIs@RoshanaPitigala不,使用正则表达式不是强制性的。我在网上找到的东西似乎满足了我所有的验证要求。谢谢。这很有效,你让我的正则表达式看起来很不错cer和shorter:)感谢您提供DateTimeFormatter上的信息。我不知道那件事。