I’m trying to separate the hours, minutes, seconds, and milliseconds from an inputed time. Right now I have
public MillisTime(String str)
throws IllegalArgumentException {
// Initialize values so that missing fields default to 0.
int hours = 0, minutes = 0, seconds = 0, millis = 0;
// Use Scanner class to parse the time string.
// Catch InputMismatchException and rethrow IllegalArgumentException.
Scanner scn = new Scanner(str);
scn.useDelimiter(":");
try {
if (scn.hasNext()) hours = scn.nextInt();
if (scn.hasNext()) minutes = scn.nextInt();
if (scn.hasNext()) seconds = scn.nextInt();
scn.useDelimiter(".");
if (scn.hasNext()) millis = scn.nextInt();
}
catch (InputMismatchException ex) {
throw new IllegalArgumentException(
"String Input Mismatch Exception: " + str);
}
scn.close();
this.setAllFields(hours, minutes, seconds, millis);
}
The input it is receiving is "16:5:7.009" and results in a String Input Mismatch Exception. If I take out the lines that look for the period and millis, and input something like 3:45 it works. How do I make this work to find : and .?
The exception occurs because with a delimiter of “:”, the subcomponents are
{16, 5, 7.009}. 7.009 is not an integer so when you callscanner.nextInt()for the third time you get the exception.Keep in mind that the delimiter scanner uses can be a regEx pattern, so it’s possible for the delimiter to be
. OR :at the same time: