Ask Question
16 December, 00:21

Design a program that will receive a valid time in the 12-hour format (e. g. 11:05 PM) and convert it to its equivalent 24-hour format (e. g. 2305). Assume 0000 in 24-hour format is 12:00AM in 12-hour format. The program should continue accepting inputs until a sentinel value of 99:99AM is entered. Ex: If the input is:09:04AM 10:45AM 11:23AM 99:99AMthe output is:0904 1045 1123Hints:Use System. out. printf statements using "d" (Links to an external site.) to match output format. Use Integer. valueOf (s) (Links to an external site.), where s is a String variable, to covert String to int.

+4
Answers (1)
  1. 16 December, 03:47
    0
    see explaination for program code

    Explanation:

    /Convert 12-hour time to 24-hour time format

    import java. io.*;

    public class Main

    {

    public static void main (String[] args) throws IOException {

    BufferedReader br=new BufferedReader (new InputStreamReader (System. in));

    String str=br. readLine ();

    while (! str. equals ("99:99AM")) {

    System. out. println (getConvertedTime (str));

    str=br. readLine ();

    }

    }

    public static String getConvertedTime (String str) {

    String s=str. substring (str. length () - 2);

    String[] hoursAndMinutes=str. substring (0,5). split (":");

    if (s. equals ("AM")) {

    //if the time is in AM then we can use same hours and minutes except for 12th hour so we need

    //special case for that if it is 12th hour we will use "00" instead of 12 for other we can use same hours

    if (hoursAndMinutes[0]. equals ("12")) return "00"+hoursAndMinutes[1];

    else return hoursAndMinutes[0]+hoursAndMinutes[1];

    }

    else{

    //if the time is in PM we need to add hours to 12 unless the hour is 12 in case of 12 we need to keep it as it is

    if (hoursAndMinutes[0]. equals ("12")) return "12"+hoursAndMinutes[1];

    else{

    int hours=Integer. valueOf (hoursAndMinutes[0]);

    hoursAndMinutes[0]=String. valueOf (12+hours);

    return hoursAndMinutes[0]+hoursAndMinutes[1];

    }

    }

    }

    }
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Design a program that will receive a valid time in the 12-hour format (e. g. 11:05 PM) and convert it to its equivalent 24-hour format (e. ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers