简体   繁体   中英

How do I compare values from lists against parameters in java?

I am trying to create a function that that checks if a level is held within an SQLite database. If it is, and the new score is greater than the score in the table then I want to edit it. I have created an edit function that seems to work fine and an add to database function that is called when the level being checked doesn't exist.

Here is my function

    void isHighScore(String level, int score) {
    List<String> scores = getHighScore();
    List<String> levels = getHighScoreLevel();

    for (int i = 0; i < levels.size(); i++) {

        int scoreVal = Integer.parseInt(scores.get(i));
        String levelVal = levels.get(i).toString();

        if (levelVal == level && scoreVal < score) {
            try {
                editScore(level, score);
            } catch (Exception e) {}
        }
    }
    if (!levels.contains(level)) {
        createHighScoreEntry(level, score);
    }
}

So far, only the create entry function is working, so my main problem resides in the for loop. Any help will be greatly appreciated.

You shouldn't be using == to compare strings because it doesn't check to see if the strings are actually equal. What you should be using is String.equals() or String.compare() or String.contains()

String.equals() checks to see if they are equal. If so it returns true

String.compare() checks to see if they are equal. If they are it returns 0 if not it returns -1 or 1 depending on the differences.

String.contains() is more generic and checks to see if a word, character or phrase is contained in your string if it is it returns true.

You can use this site as a reference for what each does http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

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