Reputation: 7
I need to test whether a String input date of (mm/dd/yyyy) is valid. The criteria is that of a normal calendar, specifically with my problem the month needs to be between 1 and 12. For whatever reason if I enter what should be a valid month, and the input itself should be true based on my if statement, my program is reading it as false.
For instance if I input 01/01/2000, the int month will = 1. Therefore the month is greater than 0 and less than 13. But instead the program reads it as false and I can't figure out why. Thanks
import java.util.Scanner;
public class C3PP4_Benjamin_Crosta_CTIM15701 {
public static void main(String[] args) {
String inputDate, monthString, dayString, yearString;
boolean validMonth, leapYear;
Scanner keyboard = new Scanner(System. in );
//user input
System.out.println("Please enter date. (mm/dd/yyyy)");
inputDate = keyboard.nextLine();
//PROCESSING
monthString = inputDate.substring(0, 2);
dayString = inputDate.substring(3, 5);
yearString = inputDate.substring(6, 10);
//String to int conversion
int month = Integer.parseInt(monthString);
int day = Integer.parseInt(dayString);
int year = Integer.parseInt(yearString);
//months
if ((month > 0 && month < 13)) validMonth = true;
else validMonth = false;
System.out.println("Your date is invalid because the month you entered does not exist.");
}
}
Upvotes: 0
Views: 64
Reputation: 1494
if (month > 0 && month < 13){
validMonth = true;
} else {
validMonth = false;
System.out.println("Your date is invalid because the month you entered does not exist.");
}
If you do not use curly brackets it will only execute one line below, also use single brackets for this if statement
You can also use split by ('/'):
String date = "01/01/1970";
String[] split = date.split("/");
int day = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int year = Integer.parseInt(split[2]);
Upvotes: 2