简体   繁体   中英

Using a Ternary Operator to a “0” within the statement

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();
        }

    }
}

How do I get the extra 0 in front of numbers less than 10.

You don't, while the target variable is of type int . An int is just a number, not a string - whereas "0" + Hours is a string.

int values don't contain any sort of string representation - the number sixteen is just as much "0x10" or "0b10000" as it is "16"... or even "00016" if your decimal representation allows much digits. ("00016" may be mis-interpreted as fourteen, however, if it's parsed as an octal string...)

Use DecimalFormat to convert numbers into strings in your desired format, or String.format , or possibly just PrintStream.printf if you want to write it straight to the console.

I'd also strongly recommend that you use camelCase for your local variables, and only declare them when you first need them.

也许你应该使用

System.out.printf("%02d:%02d%n", Hours, Minutes);

You are confusing int and String types:

int HoursInput;
//...
HoursInput = Hours < 10 ? "0" + Hours : Hours;

There are two problems with your code: you are trying to store string "07" (or similar) in an int . Secondly even if it was possible, 07 is equivalent to 7 as far as integer types are concerned (well, leading 0 has a special octal meaning, but that's not the point).

Try this instead:

String hoursInput;
//...
hoursInput = Hours < 10 ? "0" + Hours : "" + Hours;

您必须使用String变量或使用String类中的格式方法(类似于来自c的sprintf)。

String time = String.format("%02d:%02d", hours, minutes );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM