is it even possible to add a 0 in java with terny operators?

前端 未结 3 998
死守一世寂寞
死守一世寂寞 2021-01-29 11:16

Hi I\'ve tried everything from terny operators, if else statements and parsing the int to a string, I am making a clock that reads 4:01 4:02 but instead it outputs 4:1

t

3条回答
  •  情深已故
    2021-01-29 11:56

    You can simply use String.format(pattern,data) with pattern %02d

    • % represents start of pattern
    • 2 means that input should be written as at least two characters __
    • 0 but if input is shorter than two characters fill rest with 0 _a -> 0a
    • d is short from digit

    which all means that digit passed digit should be written using two characters and in case there would be empty space (number is too short like 0, 1, 2 till 9) fill space before it with 0.

    More at Formatter documentation


    Demo:

    String formatted = String.format("%02d:%02d", 4,2);
    System.out.println(formatted);
    

    Output: 04:02

提交回复
热议问题