繁体   English   中英

将整数格式化为两位数

[英]Formating an integer to two digits

我正在制作游戏并且我正在尝试显示高分。 老实说,我不知道我在做什么。 我真的可以使用一些帮助。 我想以两位数显示高分(例如 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);
        }
    }
}

使用字符串格式

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

请参阅javadoc

请记住,这是 Java,而不是仅与 Android 相关。 String.format是一种Java 方法,与Android 无关。

Android 是使用 Java 构建的。 尝试更多地了解什么是 Java、它在哪里结束以及 Android 在哪里开始使您的学习过程更好,因为您不应该搜索“Android 两位整数”。 您应该搜索“Java 两位数整数”。

所以你需要把你的号码格式化成一个字符串。 当您使用 highScore.setText 时,它会自动为您完成。 相反,您需要使用 String.format()

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

对于您需要的共享首选项。

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