简体   繁体   中英

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).

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

Remember, this is Java, not Android related only. String.format is a Java method, nothing to do with Android.

Android is built using 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". You should search for "Java two digits integer".

So you need to take your number and format it to a string. It is done automatically for you when you use highScore.setText. Instead you need to use 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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