If you're first token is > 12 and <= 23, subtract 12. Simple as that. The second token won't need changing but that assumes you're ensuring it to be between 0 and 59 inclusive (and hour has been validated as 00-23)
Thank you for the info. Just one question though...
Say if the person puts the correct hour and yet the minutes are beyond the 0-59 range, how can I make sure that it does not print out "The time is 1:73 PM" (as an example)?
if (token < 0 || token > 59)
{
throw new IllegalArgumentException("Minutes must be between 0 and 59!");
}
Thats when token is of type int. All you do is try/catch it and reloop. You can force it to be an int without casting by using scanner and asking for the next int. If its not an int, it will toss an exception.
If you want it as a string (00 - 59), you'd need to check the values and compare them between each character. Cast to an int (with a try), and use appropriate error checking for 0-5 and 0-9.
Thank you for your help This is what I have so far...I would like to have the input separated into two integers (one for hour and one for minutes) but I have no clue what to do here...
This is the main part
Code:
import java.util.*;
public class Main{
public static void main(String[] args){
//initialize variables
int time = 0;
int hour = 0;
int minute = 0;
//initialize the scanner
Scanner key = new Scanner(System.in);
//ask the person to enter the data
System.out.print("Enter time in 24-hour format: ");
//enter the data
try{
time = key.nextInt();
//check to see if time is out of range, throw exception
if(hour<0 || hour>23 && minute<0 || minute>59)
throw new WrongTimeException();
//check to see if hour is less than 12
if (hour<12)
{
System.out.println("That is the same as: " + hour + ":" + minute + "A.M.");
}
//check to see if hour is equal to 12
if (hour==12)
{
System.out.println("That is the same as: " + hour + ":" + minute + "P.M.");
}
//check to see if it is more than 12
//subtract the number from 12 in this case
if (hour>12)
{
hour=hour-12;
System.out.println("That is the same as: " + hour + ":" + minute + "P.M.");
}
}catch(WrongTimeException e){
System.out.println(e.getMessage());
}
}
}
And this is for the exception class
Code:
public class WrongTimeException extends Exception{
public WrongTimeException(){
super("Wrong Time" + hour + ":" + minute);
}
}