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

时间:2015-10-26 14:07:32

标签: java android methods return boolean

我在使用布尔方法返回的值时遇到问题。

我正在测试的是首先有效的分数:

 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消息对其进行了测试)。

3 个答案:

答案 0 :(得分:2)

您正在呼叫isValidScore()两次,并忽略第一次呼叫的结果。你应该删除它。

public void enterClicked(View sender) {

    isValidScore(); // remove this line

    if (isValidScore()) {
        ...
    } else {
        return;
    }

}

答案 1 :(得分:0)

你可以试试这个:

    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;

答案 2 :(得分:0)

以下是我对你上面提出的问题的建议。

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
    }