求问下面的程序该怎么修改
class GuessGame {Player p1;
Player p2;
Player p3;
void startGame() {
p1 = new Player();
p2 = new Player();
p3 = new Player();
int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
int targetNumber = (int) (Math.random() * 10);
System.out.println("I'm thinking of a number between 0and 9...");
while (true) {
System.out.println("Number to guess is" + targetNumber);
p1.guess();
p2.guess();
p3.guess();
guessp1 = p1.number;
System.out.println("Player one guessed " + guessp1);
guessp2 = p2.number;
System.out.println("Player two guessed " + guessp2);
guessp3 = p3.number;
System.out.println("Player three guessed " + guessp3);
if (guessp1 == targetNumber) {
p1isRight = true;
}
if (guessp2 == targetNumber) {
p2isRight = true;
}
if (guessp3 == targetNumber) {
p3isRight = true;
}
if (p1isRight || p2isRight || p3isRight) {
System.out.println("We have a winner!");
System.out.println("Player one is right?" + p1isRight);
System.out.println("Player two is right?" + p2isRight);
System.out.println("Player three is right?" + p3isRight);
break; // 游戏结束,终止循环
} else {
System.out.println("Players will have to try again.");
} // if/else结束
} // while循环结束
} // 方法结束
} // 类结束
class Player {
int number = 0;
public void guess() {
number = (int) (Math.random() * 10);
System.out.println("I'm guessing" + number);
}
}
public class GameLauncher {
public static void main(String[] args) {
GameLauncher game = new GameLauncher();
game.startGame();
}
} 类 --------------------编程问答-------------------- 就是运行时说“game.startGame();”中的startGame()为定于、可是在之前我已经定义了啊、、求问大神该怎么改程序 --------------------编程问答-------------------- startGame() 在GuessGame定义的,类GameLauncher里没有。
试试:
GuessGame game = new GuessGame(); --------------------编程问答-------------------- GameLauncher game = new GameLauncher();
game.startGame();这里你实例化的是GameLauncher这个类,而这个类里是没有startGame这个方法的。你的方法其实是在GuessGame类里,所以你应该实例化这个类才行 --------------------编程问答--------------------
根据类创建对象,然后用对象调用类中存在的方法 ------这句话请你记住!
现在,我就根据这句话,帮你改改程序:
GuessGame game = new GuessGame();//根据GuessGame类创建其相关的对象game;
game.startGame();//由于GuessGame中包含startGame()这个函数,所以GuessGame类的对象game可调用该函数。
-------------------------------
程序修改完毕 --------------------编程问答-------------------- 应该是创建错对象了吧,估计LZ想创建GuessGame game = new GuessGame();
结果一不小心写成GameLauncher game = new GameLauncher();
补充:Java , Java SE