Java将字符串格式化为小数位

use*_*603 0 java

我喜欢游戏的军事和有那个报时顶部的一栏(例如),当它在它说4日上午4:06:6是有办法,我可以改变说04:06,但也说(例子)11:45而不是011:045.

这是时间等级:

public class Hud {

    public int x, y;
    public int money = 1000;
    public int reputation = 5;
    public int wifi = 3;

    public int time = 0;
    public int timer = 10;
    public int minute = 50;
    public int hour = 10;

    public Hud(int x, int y) {
        this.x = x;
        this.y = y;

    }

    public void tick() {
        if (time >= timer) {
            time = 0;
            minute++;
        } else if (time <= timer) {
            time++;
        }
        if (minute >= 60) {
            minute = 0;
            hour++;
        }
        if (hour >= 24) {
            hour = 0;
        }
    }

    public void render(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,       RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g2.setRenderingHints(rh);

        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(x, y, Comp.size.width + 9, 20);

        g.setColor(Color.DARK_GRAY);
        g.drawRect(x, y, Comp.size.width + 9, 20);

        // money

        g.setColor(Color.yellow);
        g.setFont(new Font("italic", Font.BOLD, 15));
        g.drawString("€ " + money, 10, 17);

        // reputation

        g.setColor(Color.black);
        g.setFont(new Font("italic", Font.BOLD, 15));
        g.drawString("Rep: " + reputation, 100, 16);

        // time

        g.setColor(Color.black);
        g.setFont(new Font("italic", Font.BOLD, 15));
        g.drawString("" + hour + ":" + minute, Comp.size.width / 2 - 20, 16);

    }
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

这与Font完全无关(所以我不确定你为什么在你的问题标题中提到Font)和所有与数字格式有关的事情.你可以这样做:

String displayString = String.format("%02d:%02d", minutes, seconds);
Run Code Online (Sandbox Code Playgroud)

这样做是将分钟和秒中的整数格式化为两位数的字符串,如果int只有一位数字,则前缀为"0".

"%02d"ARE格式说明字符串帮助的String.format或java.util.Formatter中知道你是怎么想格式化数字.该%通知格式,这是一个格式说明.02意味着将其设为2位数,并0在需要时预先挂起b.d表示它是十进制数.

例如,

  g.setColor(Color.black);
  g.setFont(new Font("italic", Font.BOLD, 15));
  String displayString = String.format("%02d:%02d", hour, minute);
  g.drawString(displayString, Comp.size.width / 2 - 20, 16);
Run Code Online (Sandbox Code Playgroud)