我是一个尝试Java的新蜜蜂。
我正在尝试编写一个小数字猜谜游戏,计算机选择一个数字,然后3个玩家轮流猜测数字。无论玩家猜对了,都只能猜出一个数字。
以下是我的完整代码。 checkGuess()方法存在一些问题(无限循环),但我无法发现它是什么。你能看一看,看看我哪里出错了吗?
import java.util.ArrayList;
public class game {
private player[] p = new player[3];
private int guess;
private ArrayList<Integer> guesses = new ArrayList<Integer>();
public void start() {
int x=0;
while(x<3) {
p[x] = new player();
p[x].setName(x);
x = x + 1;
}
guess = (int) (Math.random() * 10);
System.out.println("I'm guessing " + guess);
int count = 1;
while(true) {
int y = 0;
boolean b = false;
while(y<3) {
boolean searchGuess = true;
while(searchGuess = true) {
int temp = p[y].guessNum();
searchGuess = checkGuess(temp);
if (searchGuess == false) {
System.out.println("Player " + (y+1) + " guessed " + p[y].getNum());
}//end if
}// end while
if (searchGuess==false) {
System.out.println(p[y].getName() + " guessed " + p[y].getNum());
}//end if
if (p[y].getNum() == guess) {
System.out.println("" + p[y].getName() + " guessed correct number in " + count + " guesses. Game over.");
b = true;
break;
}//end if
y = y + 1;
}//end loop
if (b == true) {
break;
}
count = count + 1;
}//end loop
}//end start
public boolean checkGuess(int tempGuess) {
boolean found = false;
if(guesses.contains(tempGuess)) {
found = true;
} else {
guesses.add(tempGuess);
}//end if
return found;
}//end checkGuess
}//end game
public class player {
private int num;
private String name;
public int guessNum() {
num = (int) (Math.random() * 10);
System.out.println("in guessnum");
return num;
}//end guessnum
public void setName(int x) {
name = "Player " + x;
}//end setName
public int getNum() {
return num;
}//end getNum
public String getName() {
return name;
}//end getName
}//end class
答案 0 :(得分:5)
您在searchGuess
循环的条件下分配给while
。相反,请使用while(searchGuess == true)
或简单while(searchGuess)
。