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

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

问题描述

我是 Java 初学者,我正在使用 thenewboston 的 Java 教程 (youtube).在教程 36-37,他开始使用 String.format();他在过去的教程中没有解释.这是他正在制作的课程的代码:

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

所以他正在做的是他正在做某种军事时间课程并使用字符串格式.所以我要问的是是否有人可以向我解释 String.format() 是如何工作的以及上面的格式是如何工作的.感谢您的帮助!

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!

推荐答案

与 C 的 printf() 工作原理相同.

It works same as printf() of C.

%s for String 
%d for int 
%f for float

前进

String.format("%02d", 8)

输出:08

String.format("%02d", 10)

输出:10

String.format("%04d", 10)

输出:0010

所以基本上,它会在作为第二个参数给出的表达式、变量或原始类型之前填充 0 的数字,0 将以这样的方式填充,即所有数字都满足 String API 格式方法的第一个参数.

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天全站免登陆