Reputation: 115
I'm having trouble using a returned value from a boolean method.
I am testing is a score valid firstly:
public boolean isValidScore() {
boolean isScoreValid = true;
scoreHit = Integer.parseInt(scored.getText().toString());//convert the 3 dart score to store it as an integer
int[] invalidScores = {179, 178, 176, 175, 173, 172, 169, 168, 166, 165, 163, 162};
boolean invalidNumHit = false;
for (int i = 0; i < invalidScores.length; i++) {
if (scoreHit == invalidScores[i]) {
invalidNumHit = true;
}
}
if (scoreHit > 180 || scoreHit > scoreLeft[player] || scoreHit + 1 == scoreLeft[player] || (scoreHit == 159 && scoreLeft[player] == 159) || invalidNumHit) {
//won't adjust score left if invalid score/checkout entered
Toast toast = Toast.makeText(getApplicationContext(),
"You've entered an invalid score, Try again!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 75);
toast.show();
scored.setText("0");//have to reset score to zero as won't do below as will return from method if invalid score
isScoreValid = false;//will exit method i.e. won't adjust scores and stats and switch player if invalid score entered.
}
return isScoreValid;
}
Then I am going into a method which calls this method - I want to then exit from this enterClicked() method if the value is false - here is how I coded this:
public void enterClicked(View sender) {
isValidScore();
if (isValidScore()) {
} else {
return;//exit method if invalid score entered.
}
//is more code here.....
}
It appears the value for isValidScore() is always true - even when I input an invalid score (I tested it with a toast message).
Upvotes: 0
Views: 306
Reputation: 2514
Below is my suggestion,for the Question that you have raised above.
public void enterClicked(View sender) {
boolean validScore = isValidScore();
if (validScore == true) {
//Do Something
} else {
return;//exit method if invalid score entered.
}
//Default Code to be excuted
}
Upvotes: 0
Reputation: 2220
Can you try this:
if (scoreHit > 180 || scoreHit > scoreLeft[player] || scoreHit + 1 == scoreLeft[player] || (scoreHit == 159 && scoreLeft[player] == 159) || invalidNumHit) {
//won't adjust score left if invalid score/checkout entered
Toast toast = Toast.makeText(getApplicationContext(),
"You've entered an invalid score, Try again!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 75);
toast.show();
scored.setText("0");//have to reset score to zero as won't do below as will return from method if invalid score
return false;//will exit method i.e. won't adjust scores and stats and switch player if invalid score entered.
}
return true;
Upvotes: 0
Reputation: 393946
You are calling isValidScore()
twice, and ignoring the result of the first call. You should remove it.
public void enterClicked(View sender) {
isValidScore(); // remove this line
if (isValidScore()) {
...
} else {
return;
}
}
Upvotes: 2