Hi I am trying to write a code that gives an output similar to
Enter time in 24-hour notation:
13:07
That is the same as
1:07 PM
Again? (y/n)
y
Enter time in 24-hour notation:
10:15
That is the same as
10:15 AM
Again? (y/n)
y
Enter time in 24-hour notation:
10:65
There is no such time as 10:65
Try Again:
Enter time in 24-hour notation:
16:05
That is the same as
4:05 PM
Again? (y/n)
n
End of program
But I have ended up making a few errors and I am unable to figure it out.
public class prp {
public static void main(String[] args) {
while (true) //add the remaining logic
{
System.out.println("Enter time in 24-hour notation HH:MM");
Scanner x = new Scanner(System.in);
String newhr = x.nextLine();
String hr[] = newhr.split(":");
int hours = Integer.parseInt(hr[0]);//HH
int minutes = Integer.parseInt(hr[1]);//MM
if ((hours >= 00 && hours <= 24) && (minutes >= 00 && minutes <= 59)) {
System.out.println("That is the same as: ");
if (hours <= 12) {
System.out.println(hours + ":" + minutes + " AM");
//System.exit(0);
} else if (hours > 12 && hours < 24) {
int hoursnew = hours - 12;
System.out.println(hoursnew + ":" + minutes + " PM");
//System.exit(0);
}
} else {
System.out.println("There is no such time as " + hours + " : " + minutes);
System.out.println("Try Again!");
//continue;
}
System.out.println("Again? [y/n]");
Scanner y = new Scanner(System.in);
String newyn = y.nextLine();
if (newyn == "y" || newyn == "n") {
if (newyn == "y") {
continue;
} else {
System.out.println("End of program");
System.exit(0);
//break;
}
}//end of while
}
}
}
The program displays error while inputting non-integers. Furthermore it is not breaking. I am suppose to create another exception class called TimeFormatException If the user enters an illegal time, like 10:65, or like ab:cd.