gpt4 book ai didi

java - 初学者 : Number Guessing Game

转载 作者:行者123 更新时间:2023-11-29 07:51:30 25 4
gpt4 key购买 nike

我是一只尝试 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

最佳答案

您在 while 循环的条件下分配给 searchGuess。相反,使用 while(searchGuess == true) 或简单地使用 while(searchGuess)

关于java - 初学者 : Number Guessing Game,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20776358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com