我正在用java代码创建一个Guessing游戏程序。我遇到了主类和测试类运行的问题。任何帮助,将不胜感激。游戏的说明是计算机生成随机#,用户必须猜测7个或更少的猜测数。如果猜测超过7,则游戏结束并询问用户是否想再次玩游戏?'
这是我的猜测课程:
import java.util.Random;
public class Guess
{
int computersNumber; // A random number picked by the computer.
int usersGuess = 0; // A number entered by user as a guess.
int guessCount = 0; // Number of guesses the user has made.
Random random = new Random();
int randomNumber = random.nextInt(100);
public Guess(int n)
{
usersGuess = n;
}
public boolean getGuess()
{
boolean isValid = false;
if (isValid)
{
return false;
}
if (usersGuess == computersNumber)
{
return true;
}
return isValid;
}
public boolean isGuessCorrect()
{
return getGuess() == computersNumber;
}
public int getCount()
{
guessCount ++;
return guessCount;
}
boolean playAgain;
}
测试员/主要课程:
import java.util.Scanner;
public class GuessTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Let's play a game!");
System.out.println();
System.out.println("The computer will generate a number between 0 and 100. You will have up to seven guesses"
+ "to figure out what the number is. Good luck!");
System.out.println();
System.out.print("What is your first guess? ");
int n = in.nextInt();
Guess guess = new Guess(n);
if (guess.getGuess == computersNumber)
{
System.out.println("That's Correct! ");
}
if (getCount == 7)
{
System.out.println("You lose, you didn't get the number in 7 guesses.");
}
System.out.println("Would you like to play again? ");
in.nextBoolean();
System.out.println();
System.out.println("Thanks for playing.");
in.close();
}
}
答案 0 :(得分:0)
您的代码中有一些不能编译的东西。你发布了所有代码吗?
首先要做的事情:如果您有class
Guess
并且想要访问其方法,则需要首先实例化Object
class
:
int n = in.nextInt();
Guess guess = new Guess(n);
接下来,为了实际访问guess
的方法,它的写法如下:
if (guess.getGuess() == computersNumber) {
System.out.println("That's Correct! ");
}
但是在您的示例中,变量computersNumber
未在主类中定义,但它是Guess
类的成员。由于computersNumber
和方法getGuess()
都是Guess
类的一部分,因此最好从该类中实际访问它们并在那里进行比较。也许在一个单独的方法中:
public class Guess{
....
public boolean isGuessCorrect(){
return getGuess() == computersNumber;
}
}
我在Guess
类中看到的另一件事是你在getGuess()
中访问了一些未定义的布尔变量:
if (!isValid) {
return false;
}
isValid
来自哪里?在哪里定义?
编辑:有点暗示道路:
您可以生成0到100之间的随机数,如下所示:
Random random = new Random();
int randomNumber = random.nextInt(100); // this will be a number between 0 and 100
int another = random.nextInt(1000); // you can reuse the random object and generate more numbers