Java 用户输入 YY-MM-DD 格式

Java User input YY-MM-DD format

这是关于数据结构的作业,我似乎找不到我需要的确切答案。

我正在尝试接受用户输入的日期,最好是 YY-MM-DD 格式,然后检查有效性。如果无效,循环直到有效。这真的看起来很乏味,我收到了两个非法开始的表达式错误。

我在 Google 和 Whosebug 上进行了搜索,但只找到了涉及 Date

的内容
public String hireDate(){
    Scanner input = new Scanner(System.in);
    boolean answer = false;
    while(answer == false){
        String temp = input.nextLine();
        if((temp.charAt(0) >= 0 && temp.charAt(0) <= 9) && (temp.charAt(1)
                >= 0 && temp.charAt(1) <= 9) && (temp.charAt(2) == -) 
                && (temp.charAt(3) >= 0 && temp.charAt(3) <= 9) && (temp.charAt(4)
                >= 0 && temp.charAt(4) <= 9) && (temp.charAt(5) == -)
                && (temp.charAt(6) >= 0 && temp.charAt(6) <= 9)){
            answer = true;
        } else {
            answer = false;
        }    
    }
    return temp;
}

您可以使用 Regex 轻松完成。只需检查您的输入字符串是否与您的模式匹配 (YY-MM-DD)

if (temp.matches("\d{2}-\d{2}-\d{2}")) 
temp.charAt(1)>=0

您正在比较一个字符和一个整数。