簡體   English   中英

布爾值不會返回false

[英]boolean will not return false

import java.util.Random;
import java.util.Scanner;


public class HiLo {

/**
 * Nick Jones
 * 2/10/2015
 * High or Low
 */
public static boolean high()   {
    int x;
    boolean answer;

    Random randomGenerator = new Random();
    x = randomGenerator.nextInt(9 - 1) + 1;
    System.out.println("number is " + x);

if (x > 6 && x < 14) {
    System.out.println("You win!");
    answer = true;
    return answer;
} else {
    System.out.println("You lose!");
    answer = false;
    return answer;
}
}


public static boolean low()   {
    int x;
    boolean answer;

    Random randomGenerator = new Random();
    x = randomGenerator.nextInt(9 - 1) + 1;
    System.out.println("number is " + x);

    if (x > 0 && x < 7) {
        System.out.println("You win!");
        answer = true;
        return answer;
    } else {
        System.out.println("You lose!");
        answer = false;
        return answer;
    }
    }


public static void main(String[] args) {
    int points = 1000;
    int risk;
    int guess;
    boolean answer;
    int again;

    do {
    System.out.println("you have " + points + " points.");
    Scanner input = new Scanner (System.in);

    System.out.println ("Input number of points to risk:  ");
    risk = input.nextInt();
    System.out.println ("predict <1-high, 0-low>:  ");
    guess = input.nextInt();

    if (guess == 1) {
        answer = high();
    } if (guess == 0) {
        answer = low();
    }

    if (answer = true) {
        points = points + (risk*2);
    **} if (answer = false) {
        points = points - risk;**
    }
    System.out.println("You have " + points + " points.");

    System.out.println("play again?<yes-1, no-0>  ");
    again = input.nextInt();

    } while (again == 1);





}

}

該程序旨在從得分為1000分的玩家開始,然后隨機生成一個數字,然后他們選擇得分的數量作為“風險”,然后選擇高或低(低-1-6。高-8-13 ),如果他們的猜測正確,那么他們的風險就會加倍,並加回到他們的得分中。 如果不正確,則從得分中減去風險。 我的布爾語句似乎正在阻止程序

if (answer = false) {
    points = points - risk;

這部分,所以我的布爾值永遠不會返回false,這就是我認為我的問題所在。 因為在運行時,它只會讓玩家獲勝,而永遠不會輸,它會輸出“您輸了”,但仍會像贏得點一樣添加積分。

您正在使用賦值運算符= ,因此answer始終為true 相等的比較運算符是== ,因為您已經在代碼的其他地方使用過。 但是answer已經是布爾值。 無需使用==進行比較; 只是使用它。 更改

if (answer = true) {
    points = points + (risk*2);
} if (answer = false) {
    points = points - risk;
}

if (answer) {
    points = points + (risk*2);
} else {
    points = points - risk;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM