I’m trying to format a time using a variable input. If a user enter an hour as 1 – 9 the out put would include a “0”, and the same for minutes. So far if a user enters 1 hour 3 minutes the output reads 1:3 instead of 01:03.
How do I get the extra 0 in front of numbers less than 10.
Here’s the code…..
import java.util.Scanner;
public class FormatTime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int MinutesInput;
int HoursInput;
int Hours;
int Minutes;
{
System.out.println("Enter hours between 1 and 24");
Hours = input.nextInt();
System.out.println("Enter minutes between 1 and 59");
Minutes = input.nextInt();
{
**//THIS NEXT LINE IS THE PROBLEM**
HoursInput = Hours < 10 ? "0" + Hours : Hours;
System.out.print(HoursInput + ":");
}
{
**//THIS NEXT LINE IS THE PROBLEM**
MinutesInput = (Minutes < 10) ? "0" + Minutes : (Minutes);
System.out.print(MinutesInput);
}
System.out.println();
}
}
}
You are confusing
intandStringtypes:There are two problems with your code: you are trying to store string
"07"(or similar) in anint. Secondly even if it was possible,07is equivalent to7as far as integer types are concerned (well, leading0has a special octal meaning, but that’s not the point).Try this instead: