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();
}
CodePudding user response:
You can wrap your code inside while loop in a try-catch block. It will catch your exception without terminating the program.
CodePudding user response:
One approach is to catch the exceptions. That's the way to deal with the potential exceptions from parseInt
; e.g. when the value isn't a valid integer.
Another approach is to make the code more robust so that the exception isn't thrown at all. For example:
check the results of the
indexOf
calls to make sure they are not -1 ... which means "not found", anddon't make assumptions about the number of characters in each field; e.g.
lineString.length() - 4
consider using
String.trim()
to get rid of additional whitespace.
I think you will need to use both approaches. The key thing is to think of all the mistakes that the user might make and allow for them. It is also a good idea to write your own tests.