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

梦想与她 提交于 2019-12-31 07:44:06

问题


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

this is my java code, is it possible to add a 0? or I am going to need something else?

package bank;

import java.util.*;

/**
 *
 * @author will
 */
public class dClock {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Calendar time = Calendar.getInstance();

        int min = 1;//time.get(Calendar.MINUTE);
        int hour =  time.get(Calendar.HOUR_OF_DAY);
        int blank = Integer.parseInt("0");

        int hourOfDay = ((hour > 12) ? (hour - 12) : hour);
        int zero = ((min > 10 ) ? min : blank+min);        
        System.out.println("The time is " + hourOfDay + ":" + zero );


    }

}

回答1:


Look at Java Tutorial: Formatting Numeric Print Output.

For example:

  long n = 461012;
  System.out.format("%08d%n", n);    //  -->  "00461012"

Another example:

  Calendar c = Calendar.getInstance();
  System.out.format("%tl:%tM %tp%n", c, c, c);  // -->  "2:34 am"



回答2:


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




回答3:


The problem is this line:

int blank = Integer.parseInt("0");

Since your blank is an integer 0, blank + min will be the same as min. Try just using "0" without changing the type.

Also, as David Wallace mentions, you should replace (min > 10 ) with (min >= 10 ) or (min > 9 )



来源:https://stackoverflow.com/questions/23375049/is-it-even-possible-to-add-a-0-in-java-with-terny-operators

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!