mardi 19 février 2019

Converting String time format of HH:MM:SS (AM/PM) into Seconds

So I have this assignment that is asking us to take in a String format of time in the order of HH:MM:SSAM or HH:SS:MMPM. The constraint is that it cannot run if it is in wrong format, let it be missing any form of the AM or PM, missing a number, or if it is in 24 Hour Format.

I have the whole idea down, however for my statements, it is giving me the error of:

bad operand types for binary operator '>' incomparable types: String and int

Did I convert them improperly or am I doing something else wrong?

public static void main(String args[]) {
    //Test Methods
  String fullTime1 = "03:21:36AM";
  secondsAfterMidnight(fullTime1);
}


public static int secondsAfterMidnight(String time) {
  String[] units = time.split(":");
  int hours = Integer.parseInt(units[0]);
  int minutes = Integer.parseInt(units[1]);
  int seconds = Integer.parseInt(units[2]);
  int totalSeconds = 0;
  if (units[0] > 12 || units[1] > 59 || units[2] > 59) {  //1st Error applies to these three, units[0] > 12 units[1] > 59 units[2] > 59
     return -1;
  } else if (time.equalsIgnoreCase("AM") || time.equalsIgnoreCase("PM")) {
     totalSeconds = (hours * 3600) + (minutes * 60) + (seconds);
  } else if (time.equalsIgnoreCase("AM") && units[0] == 12) { //2nd Error applies to this units[0] == 12
     totalSeconds = (minutes * 60) + (seconds);
  } else {
     return -1;
  }

  return totalSeconds;
} 

Aucun commentaire:

Enregistrer un commentaire