Formatting using printf and format

元气小坏坏 提交于 2019-11-27 17:07:58

问题


In the following program

class ZiggyTest2 {

    public static void main(String[] args){     

        double x = 123.456;
        char c = 65;
        int i = 65;

        System.out.printf("%s",x);
        System.out.printf("%b",x);
        System.out.printf("%c",c);
        System.out.printf("%5.0f",x);
        System.out.printf("%d",i);
    }       
}

The output is

123.456trueA  12365

Can someone please explain how a double value (i.e. 123.456) is converted to a boolean (ie. true)

The reason I ask is because I know java does not allow numbers to be used for boolean values. For example, the following is not allowed in Java

if (5) {
 //do something
}

Thanks


回答1:


for "%b" : If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true".

reference




回答2:


The API documentation seems to clearly state why.

If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true".




回答3:


Because the value is of type double and this is how the %b converter works with values of this type.



来源:https://stackoverflow.com/questions/8629995/formatting-using-printf-and-format

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