To follow your format, the user must enter a time with ':' at the 3rd character position charAt(2)
and the rest of the characters (at indices 0, 1, 3 and 4) must be digits. A very quick to implement and good to learn solution is to use regex: http://www.regular-expressions.info/tutorial.html
However, I'll be showing you a simpler to understand solution using your code as a template:
- Verify that the length is 5
- Verify that the hours are correct
- Verify that the minutes are correct
- Ask the user to re-enter the value if anything is incorrect
Here's the code:
int total; // Total Minutes
String time; // Input from keyboard
final Scanner T = new Scanner(System.in);
System.out.print("Enter the time in HH:MM :");
time = T.next();
boolean correctFormat = false;
int hour = 0, minute = 0;
while (!correctFormat) {
correctFormat = true;
if (time.length() != 5)
correctFormat = false;
else {
// Get the value before the ':'
hour = Integer.parseInt(time.substring(0, 2));
if (hour >= 24 || hour < 0)
correctFormat = false;
// Get the value after the ':'
minute = Integer.parseInt(time.substring(3, 5));
if (minute >= 60 || minute < 0)
correctFormat = false;
}
if (!correctFormat) {
System.out.print("Pleaase follow the format! Enter the time in HH:MM :");
time = T.next();
}
}
// Formula of the calculation
total = hour * 60 + minute;
// Display the final value
System.out.println(time + " is " + total + " minutes.");
Further, if you want to make the code even more robust, you can check to see if the user actually enters numbers before and after the ':' by catching a 'NumberFormatException' that will be thrown from the Integer.parseInt()
method if the parameters aren't an actual number. You can do this by editing the above code to as follows:
int total; // Total Minutes
String time; // Input from keyboard
final Scanner T = new Scanner(System.in);
System.out.print("Enter the time in HH:MM :");
time = T.next();
boolean correctFormat = false;
int hour = 0, minute = 0;
while (!correctFormat) {
correctFormat = true;
if (time.length() != 5)
correctFormat = false;
else {
try {
hour = Integer.parseInt(time.substring(0, 2));
minute = Integer.parseInt(time.substring(3, 5));
} catch (NumberFormatException e) {
correctFormat = false;
}
if (correctFormat) {
if (hour >= 24 || hour < 0)
correctFormat = false;
if (minute >= 60 || minute < 0)
correctFormat = false;
}
}
if (!correctFormat) {
System.out.print("Pleaase follow the format! Enter the time in HH:MM :");
time = T.next();
}
}
// Formula of the calculation
total = hour * 60 + minute;
// Display the final value
System.out.println(time + " is " + total + " minutes.");