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是我认为我的问题。因为当它运行时它只允许玩家获胜,永远不会输,它会输出“你输了”,但仍然加上积分,好像他们已经赢了。
答案 0 :(得分:2)
您正在使用分配运算符=
,因此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;
}