简体   繁体   中英

Android Java math logic issue

I want to message the player if he score a specific score.

What I am currently using ..

if(score <= 4){
 messagePlayer("You scored 1.");

} else if(score <= 19){
 messagePlayer("You scored 1.");
 messagePlayer("You scored 5.");

} else if(score <= 49){
 messagePlayer("You scored 1.");
 messagePlayer("You scored 5.");
 messagePlayer("You scored 20.");

} else if(score <= 99){
 messagePlayer("You scored 1.");
 messagePlayer("You scored 5.");
 messagePlayer("You scored 20.");
 messagePlayer("You scored 50.");

} else if(score >= 100){
 messagePlayer("You scored 1.");
 messagePlayer("You scored 5.");
 messagePlayer("You scored 20.");
 messagePlayer("You scored 50.");
 messagePlayer("You scored 100.");
}

The scores I want are:

  • 1 Point
  • 5
  • 20
  • 50
  • 100

Is my logic 100% right and accurate? I think my first one score <= 4 is wrong , so if he gets 0 he can also get the message You scored 1 . And I am not using score == x, because I need to message the player at the end, when he finish, so his highscore like 15.

Explicitly exclude zero like this:

if(score > 0 && score <= 4){
 messagePlayer("You scored 1.");

}

Or better yet, store your boundary values in an array and solve the problem in one loop:

int[] boundaries = { 1, 5, 20, 50, 100 };

for (int i : boundaries) {
    if (score >= i) {
        messagePlayer("You scored " + i);
    }
}

The program as it exists now will always tell the user they scored 1, as long as they scored at least one, because your if-else will never make it past the first if, which will evaluate to true.

Better usage really would be to loop through your target scores an message each as the user crossed that threshold:

int[] targets = {0,1,5,20,50,100}

for (int i : targets) {
 if (score >= i) {
  messagePlayer("You scored " + i + ".")
 }
}

You can make this code much more readable:

if(score <= 4)
    messagePlayer("You scored 1.");
if(score <= 19)
    messagePlayer("You scored 5.");
if(score <= 49)
    messagePlayer("You scored 20.");
if(score <= 99)
    messagePlayer("You scored 50.");
if(score >= 100)
    messagePlayer("You scored 100.");

因此,您还需要签入第一个if语句以获取大于零的结果。您可以像这样更改第一个if语句

if(score>0 && score <= 4)

i will modify little bit your structure

if( score >0){
 messagePlayer("You scored 1.");
} 
if(score >4){
 messagePlayer("You scored 5.");

} 
if(score > 19){
 messagePlayer("You scored 20.");

}

if(score > 49){
 messagePlayer("You scored 50.");

} 
if(score > 99){
 messagePlayer("You scored 100.");
}

note that, i removed else statements

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