Complete the following method that takes a String parameter that is a time in American 12 hour format, such as "06:12 PM." The method returns a String with the same time in standard international 24 hour form. For example, given the parameter in the example above, the method would return "18:12." Values with AM correspond to times from 00:00 to 11:59 and PM for times from 12:00 to 23:59. Recall the method Integer.parseInt() takes a String parameter and returns the integer equivalent. And then simply I am supposed to create a method like so... public static String convertTime(String amerFormat) { }

Respuesta :

Answer:

public class AmericanTimeFormatting {

  public static String convertTime(String amerFormat)

  {

   

      if(amerFormat.length()<8) {

          System.out.println("Length of the input string should be 8");

          return null;

      }

   

      else if(!Character.isDigit(amerFormat.charAt(0)) && !Character.isDigit(amerFormat.charAt(1)) && !Character.isDigit(amerFormat.charAt(3)) && Character.isDigit(amerFormat.charAt(4))) {

          System.out.println("Digit is requird");

          return null;

      }

 

      else if(amerFormat.charAt(2)!=':'|| amerFormat.charAt(7)!='.') {

          System.out.println("Punctuation required");

          return null;

      }

      //Am or Pm specification check

      else if(!amerFormat.substring(5,7).equals("PM") && !amerFormat.substring(5,7).equals("AM")){

          System.out.println("Required PM or AM");

          return null;

      }

      else {

          //For PM

          if(amerFormat.substring(5,7).equals("PM")) {

              String time="";

              int hour=Integer.parseInt(amerFormat.substring(0,2));

              hour=24-(12-hour);

              time+=String.valueOf(hour)+":";

              int minute=Integer.parseInt(amerFormat.substring(3,5));

              time+=minute;

              return time;

          }

          //For AM

          else {

              return amerFormat.substring(0,5);

          }

         

      }

  }

  public static void main(String[] args) {

 

      String time=convertTime("06:12PM.");

   

      if(!time.equals(null)) {

          System.out.println("Time is "+time);

      }

  }

}