如何使用方法(Java)返回的布尔值



我在使用布尔方法的返回值时遇到了麻烦。

我正在测试的是一个有效的分数:

 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;
}

然后我进入一个调用这个方法的方法-如果值为false,我想退出这个enterClicked()方法-这是我如何编码的:

public void enterClicked(View sender) {
    isValidScore();
    if (isValidScore()) {
    } else {
        return;//exit method if invalid score entered.
    }
       //is more code here.....
}

看起来isValidScore()的值总是为true——即使我输入了一个无效的分数(我用toast消息测试了它)。

您调用isValidScore()两次,并且忽略了第一次调用的结果。你应该把它去掉。

public void enterClicked(View sender) {
    isValidScore(); // remove this line
    if (isValidScore()) {
        ...
    } else {
        return;
    }
}

你可以试试这个吗:

    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;

对于你上面提出的问题,我的建议如下:

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
    }

最新更新