如何在Java中使用String.format()? [英] How to use String.format() in Java?

查看:690
本文介绍了如何在Java中使用String.format()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者,我正在使用新波士顿的java教程(youtube)。在教程36-37他开始使用String.format();他在过去的教程中没有解释。这里是他正在创建的类的代码:

pre code $ public class tuna {
private int hour;
private int minute;
private int second;

public void setTime(int h,int m,int s){
hour =((h> = 0& h< 24)?h:0); ((m> = 0& m< 60)m:0);
秒=((s> = 0& s< 60)s:0);


public String toMilitary(){
return String.format(%02d:%02d:%02d,hour,minute,second);






$ b因此他所做的是做某种军事时间类和使用字符串格式。所以我问的是,如果有人可以向我解释String.format()是如何工作的,以及上面的格式是如何工作的。感谢您的帮助!

解决方案

它和C的printf()一样。


%s - >字符串

%d - > int

%f - > float




提前

String.format(%02d,8) - > OUTPUT:08
String.format(%02d,10) $>
String.format(%04d,10) - > OUTPUT:0010



所以基本上它会填充0表达式之前的0的数字,作为第二个参数给出的变量或原始类型,0将被填充以使得所有数字都满足格式方法的第一个参数字符串API。

I am a beginner in Java, and I'm using thenewboston's java tutorials (youtube). At tutorial 36-37 he starts using a String.format(); which he didn't explain in past tutorials. Here is the code for a class he was making:

    public class tuna {
        private int hour;
        private int minute;
        private int second;

        public void setTime(int h, int m, int s){
            hour = ((h >= 0 && h < 24) ? h : 0);
            minute = ((m >= 0 && m < 60) ? m : 0);
            second = ((s >= 0 && s < 60) ? s : 0);
        }

        public String toMilitary(){
            return String.format("%02d:%02d:%02d", hour, minute, second);
        }
    }

So what he's doing is he's doing some sort of military time class and using String formatting. So what I'm asking is if someone can explain to me how String.format() works and how the formatting above works. Thanks for the help!

解决方案

It works same as printf() of C.

%s -> String

%d -> int

%f -> float

ahead

String.format("%02d", 8) -> OUTPUT: 08 String.format("%02d", 10) -> OUTPUT: 10 String.format("%04d", 10) -> OUTPUT: 0010

so basically, it will pad number of 0's ahead of the expression, variable or primitive type given as the second argument, the 0's will be padded in such a way that all digits satisfies the first argument of format method of String API.

这篇关于如何在Java中使用String.format()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆