Hi, I'm working on an assignment where I have to convert military time to standard time. I think I mostly have it solved except for when the minutes are between 0 and 10. For example,

909 should read 9:09 am, but it prints 9:9 am.

I'm not sure how to add a 0 before the minutes in that case. Any advice would be much appreciated, thanks!

import java.util.Scanner;

public class TimeConvert 
{
    public static String militaryToOrdinaryTime(int milTime)
    {
       int hour = milTime / 100;
       int min = milTime%100;
       String period;

       if (hour < 0 || hour > 24 || min < 0 || min > 59)
       {
           return "";
       }
       else if (hour > 12)
       {
           hour = hour - 12;
           period = "pm";
       }
       else
       {
           period = "am";
       }
       if (hour == 0)
       {
           hour = 12;
       }
       else if (min == 0)
       {
           String ordTime = hour + " " + period;
           return ordTime;
       }   
       else if (min < 10 && min > 0)
       {
           // needs fixing
       }
       String ordTime = hour + ":" + min + " " + period;
       return ordTime;
    }

    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter military Time (hhmm) : ");
        int time = in.nextInt();

        System.out.println("Ordinary Time: " +militaryToOrdinaryTime(time));
    }
}

If the number of minutes is less then 10 then you need to concatenate a leading "0" to the minutes to get the two digits.

Should I convert min to a String and make min = "0" + min? Although when I do that Netbeans says "int cannot be dereferenced."

Make a String that holds the min value.

Ok, I got it to work using this:

           String min1 = String.valueOf(min);
           min1 = "0" + min1;
           String ordTime = hour + ":" + min1 + " " + period;
           return ordTime;

Although we never learned the valueOf class I assume it's ok to use. Not sure what else the teacher would have us do. Thanks for the help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.