嗨,我是编程的新手,所以我需要一些帮助。我需要制作一种方法来检查生日是否正确。例如960214,其中96是02年是月,14是日,但生日是String。所以这就是我得到的:
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(year),因为它返回false,它应该返回true。我打印年份只是为了看看出来的东西和96出来就像在顶部的例子。我做错了什么?
答案 0 :(得分:2)
Character.isDigit(year)除了char而不是数字。 Character.isDigit('5')这将返回true。
答案 1 :(得分:0)
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!
答案 2 :(得分:0)
注意:强>
如果我理解正确,您需要确保输入的字符串是数字。如果这是问题,则应使用以下代码。
<强>建议:强>
在解析整数之前,你应该检查它是否是一个数字,因为如果你立即解析它并且它是无效的,它将导致异常。
<强>代码:强>
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!
输出(&#34;输入&#34;是&#34; xx0214&#34;):
xx is not a number!