Character.IsDigit returns false 而不是整数 Java

Character.IsDigit returns false instead of true on an integer Java

嗨,我是编程新手,所以我需要一些帮助。我需要制定一种方法来检查生日是否正确。例如 960214,其中 96 是年 02 是月,14 是日,但生日是一个字符串。这就是我得到的:

private static boolean checkCorrect(String a) {

    int year = Integer.parseInt(a.substring(0,2));

    int month = Integer.parseInt(a.substring(2, 4));

    int day = Integer.parseInt(a.substring(4, 6));

    if (a.length() == 6 && Character.isDigit(year)) {
        return true;
    } else
        return false;
}

现在我停在了 Character.isDigit(年),因为它 return 错误而它应该 return 正确。我打印 year 只是为了看看会出现什么,而 96 就像上面的例子一样出现了。我做错了什么?

Character.isDigit(year) 除了字符而不是数字。 Character.isDigit('5') 这将 return 为真。

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Write your Birthday in the form yymmdd: ");
    String date = input.nextLine();
    if(checkDate(date))
      System.out.println("Your Birthday: " + date + " is valid :)");
    else
      System.out.println("Your Birthday: " + date + " is invalid :(");
  }

  public static Boolean checkDate(String date){
    if(date.length() != 6) {
      System.err.println("Please enter your Birthday in the form yymmdd... ");
      System.exit(1);
    }
    try {
      int year = Integer.parseInt(date.substring(0,2));
      int month = Integer.parseInt(date.substring(2, 4));
      int day = Integer.parseInt(date.substring(4, 6));
      if ((00<=year && year<=99) && (01<=month && month<=12) && (01<day && day<=31)) 
        return true;
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return false;
  }
}

试一试here!

注:

如果我没理解错的话,你要确定输入的String是一个数字。如果这是问题所在,则应使用以下代码。

建议:

在解析Integer之前应该检查它是否是一个数字,因为如果你立即解析它并且它是无效的,它会导致异常。

代码:

public static void main(String args[]) {
    String input = "960214"; // Sets the value of the String
    String year = input.substring(0, 2); // Finds the "year" value in the
                                            // input
    Boolean isANumber = true; // The year is thought to be a number unless
                                // proven otherwise
    try {
        Integer.parseInt(year); // Tries to parse the year into an integer
    } catch (Exception ex) { // Catches an Exception if one occurs (which
                                // would mean that the year is not an
                                // integer
        isANumber = false; // Sets the value of "isANumber" to false
    }
    if (isANumber) { // If it is a number...
        System.out.println(year + " is a number!"); // Say it is a number
    } else {
        System.out.println(year + " is not a number!"); // Say it is not a
                                                        // number
    }
}

输出:

96 is a number!

输出(当"input"为"xx0214"时):

xx is not a number!