75.7k views
3 votes
Read in a time such as 3 pm and print the equivalent military hour. Validate the input.

If the input doesn’t start with an integer, print: Error: Not an integer.
If the number isn’t between 1 and 12, print: Error: The hour must be between 1 and 12.
If the suffix isn’t "am" or "pm", print: Error: The suffix must be am or pm.
import java.util.Scanner;
public class TimeReader
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
if (in.hasNextInt())
{
int hour = in.nextInt();
if (hour>=1 && hour<=12)
{
String suffix = in.next();
if (suffix.equals("am") || suffix.equals("pm"))
{
if(suffix.equals("pm")){
hour += 12;
}
System.out.println(hour);
}
else
{
System.out.println("Error: The suffix must be am or pm.");
}
}
else
{
System.out.println("Error: The hour must be between 1 and 12.");
}
}
else
{
System.out.println("Error: Not an integer.");
}
}
}

1 Answer

2 votes

Final answer:

The code provided in Java reads a time and converts it to military hour format while validating the input for different conditions.

Step-by-step explanation:

The code provided is written in Java and it aims to read a time in the format of 3 pm and print the equivalent military hour. The input is being validated for several conditions. First, it checks if the input starts with an integer. If not, it prints an error message. Then, it checks if the hour is between 1 and 12, and if not, it prints another error message. Finally, it checks if the suffix is either 'am' or 'pm' and handles the hour conversion accordingly.

User Duncan Malashock
by
7.8k points