Hi I am newer to programming so I need some help. I need to make a method where I check if a birthday is correct. For instance 960214 where 96 is year 02 is month and 14 is day, but the birthday is a String. So here is what I got:
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;
}
Now I stopped at Character.isDigit(year) because it returns false where it should return true. I printed year just to see what comes out and 96 comes out just like in the example on top. What am I doing wrong?
Character.isDigit(year) excepts a char not a number. Character.isDigit('5') this will return true.
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;
}
}
Try it here!
Note:
If I understand correctly, you want to make sure that the inputted String is a number. The following code should if that is the issue.
Advice:
You should check if it is a number before parsing the Integer, because if you parse it immediately and it is invalid, it will cause an Exception.
Code:
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
}
}
Output:
96 is a number!
Output (When the "input" is "xx0214"):
xx is not a number!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.