简体   繁体   中英

Java Timer on an Android app

I need a little help on my android app in java.

I have a timer that check if current score is better than the best score saved and save it accordingly

Here is the code :

    if(sec< bestSec){
        Main.settings= Main.context.getSharedPreferences(GameConstants.PREFS_NAME, Main.MODE_WORLD_WRITEABLE);
        Main.editor= Main.settings.edit();
        if(mSec<10){
            Main.editor.putString("best", sec+"."+"0"+mSec);
        }else{
            Main.editor.putString("best", sec+"."+mSec);
        }
        Main.editor.putInt("bestSec", sec);
        Main.editor.putInt("bestMSec", mSec);
        Main.editor.commit();
    }else if(sec== bestSec){
        if(mSec< bestMSec){
            Main.settings= Main.context.getSharedPreferences(GameConstants.PREFS_NAME, Main.MODE_WORLD_WRITEABLE);
            Main.editor= Main.settings.edit();
            if(mSec<10){
                Main.editor.putString("best", sec+"."+"0"+mSec);
            }else{
                Main.editor.putString("best", sec+"."+mSec);
            }
            Main.editor.putInt("bestSec", sec);
            Main.editor.putInt("bestMSec", mSec);
        }
    }

My best score is : 12,89sec for exemple. If I do 11,20 or 11,92 it save nice, but if I do 12,45sec it doesn't save.

Thx for your help !

You should use double or float values to compare them correctly. If you are casting your decimal values to int, 12,89 and 12,45 will be equal to 12. The decimal part of the number will be ignored.

Use doubles or floats to make effective comparisons and use editor.putFloat() to save the values.

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