I am trying to complete a project that takes a date in the format: Month Day, Year Example: December 1, 1990. After taking in this date, I am trying to output it in the format Month/Day/Year. The method that I am expected to use is substring. I am running into issues with errors when handling misinputs. For example, if there isn't a comma, then an error occurs and the loop is terminated. I am wondering if there is a way to check each value for an error and then continue through the loop if an error is found. Here is my code so far:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
// Flag to indicate next iteration
String lineString = "";
String month;
int year;
int day;
char comma;
lineString = scnr.nextLine();
while(!lineString.equals(-1)) {
month = lineString.substring(0, lineString.indexOf(" "));
day = Integer.parseInt(lineString.substring(lineString.indexOf(" ") + 1, lineString.indexOf(',') ));
comma = lineString.charAt(lineString.indexOf(','));
year = Integer.parseInt(lineString.substring(lineString.length()-4));
System.out.println(month);
System.out.println(day);
System.out.println(comma);
System.out.println(year);
lineString = scnr.nextLine();
}
You can wrap your code inside while loop in a try-catch block. It will catch your exception without terminating the program.