简体   繁体   English

将整数格式化为两位数

[英]Formating an integer to two digits

I am making a game and I'm trying to display the highscore.我正在制作游戏并且我正在尝试显示高分。 honestly I don't know what I am doing.老实说,我不知道我在做什么。 I could really use some help.我真的可以使用一些帮助。 I want to display the highscore in two digits (eg 01, 02, 03 ... 09, 10, 11).我想以两位数显示高分(例如 01, 02, 03 ... 09, 10, 11)。

private class MainActivity extends Activity {
    private TextView highscore;
    private int hs=00;
    private TextView mtvscore;
    private int Score = 00; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mtvscore = (TextView) findViewById(R.id.score);
        mtvscore.setText("" + Score);
        highscore = (TextView) findViewById(R.id.highscorelabel);
        highscore.setText("" + hs);

        SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
        int hs = settings.getInt("HIGH_SCORE", 0);

        if (Score > hs) {
            highscore.setText(Score);

            SharedPreferences.Editor editor = settings.edit();
            editor.commit();
        } else {
            highscore.setText(score);
        }
    }
}

Use String format使用字符串格式

String twoDigitsHighscore = String.format("%02d", Score);
highscore.setText(twoDigitsHighscore);

See the javadocs请参阅javadoc

Remember, this is Java, not Android related only.请记住,这是 Java,而不是仅与 Android 相关。 String.format is a Java method, nothing to do with Android. String.format是一种Java 方法,与Android 无关。

Android is built using Java. Android 是使用 Java 构建的。 Try to learn more about what is Java, where does it ends and where Android starts to make your learning process better, as you shouldn't search for "Android two digits integer".尝试更多地了解什么是 Java、它在哪里结束以及 Android 在哪里开始使您的学习过程更好,因为您不应该搜索“Android 两位整数”。 You should search for "Java two digits integer".您应该搜索“Java 两位数整数”。

So you need to take your number and format it to a string.所以你需要把你的号码格式化成一个字符串。 It is done automatically for you when you use highScore.setText.当您使用 highScore.setText 时,它会自动为您完成。 Instead you need to use String.format()相反,您需要使用 String.format()

highscore.setText(String.format("%02d", score));

For shared preferences you need.对于您需要的共享首选项。

SharedPreferences preferences = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("HIGH_SOCRE", score);
editor.apply();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM