What am I trying to do:
I am trying to convert 4-digit wartime into a standard 12-hour time format, with a colon and added PM or AM without importing anything up to my code (I am making a method that requires nothing but java 101 technique).
My situation:
I have milTime , which I manually change around every time I run it (as indicated above, currently at 1100), until I convert it to a method and pass the job to which it will accept in milTime, and return milTimeString for the main program for printing. I am currently using BlueJ as an IDE (I'm not sure if this is the best option to use?)
Example input and output:
If 0056 were given, I should have returned 12:56. If 1125 were given, I would have to return 11:25. If 2359 were provided, I would have to return 23:59.
Problems I Need Help With
- When I execute, my am / pm boolean fails somewhere, and it always outputs pm, regardless of whether I enter 11:24 or 23:24.
- It is probably obvious that I work too much to generate output, but I donβt know an easier way (besides importing something for me that I donβt want to do).
I humbly submit to any criticism of my bloated current code and any corrections in my long request. I was looking for alternative answers, and everything included import or knowledge for me. Thank you for your time, and thank you in advance.
public class timeTest { public static void main(String []args) { int milTime = 2400; String timeString = ""; boolean pm; if (milTime >1259) { if (milTime <1200) { pm = false; } else { pm = true; } milTime = (milTime - 1200); } else { } int fourthDigit = milTime%10; milTime = milTime/10; int thirdDigit = milTime%10; milTime = milTime/10; int secondDigit = milTime%10; milTime = milTime/10; int firstDigit = milTime%10; String hoursString = thirdDigit + "" + fourthDigit; String minutesString = firstDigit + "" + secondDigit; if (firstDigit == 0 ) { minutesString = "" + secondDigit; } else { } if (secondDigit == 0) { minutesString = "12"; } else { } if (pm = true) { timeString = (minutesString + ':' + hoursString + "pm"); } else { } if (pm = false) { timeString = (minutesString + ':' + hoursString + "am"); } else { } System.out.println(timeString); } }
source share