3 回答

TA貢獻1809條經驗 獲得超8個贊
p1、p2 和 p3 在您的 GuessGame 類中聲明,因此您的 GameLauncher 方法看不到這些。您應該將這些變量設為全局變量,或者在 GameLauncher 中聲明它們,因為您的 GuessGame 不使用它們。
編輯代碼:
class GameLauncher{
public static void main(String[] args){
Player p1 = new Player();
Player p2 = new Player();
Player p3 = new Player();
GuessGame Game1 = new GuessGame();
Game1.startGame(p1);
Game1.startGame(p2);
Game1.startGame(p3);
}
}
public class GuessGame {
void startGame(Player p){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
p.guess(n);
}
}
class Player{
private int number;
Player(){
number = (int)Math.random();
}
void guess(int n){
if(number == n){
System.out.println("the correct answer");}
System.out.println("the wrong answer");
}
}

TA貢獻1850條經驗 獲得超11個贊
如果你想運行代碼:
將您的 main() 方法放在公共類中
利用 。用于訪問 GuessGame 屬性的運算符。
如果您希望您的代碼更好:
更改 GuessGame 中的訪問修飾符:public -> private 并使用 getter/setter 進行訪問。
對guess() 方法使用if/else 表達式。
公共類 GameLauncher {
public static void main(String[] args) {
GuessGame game1 = new GuessGame();
Player p1 = new Player();
Player p2 = new Player();
Player p3 = new Player();
game1.startGame(p1);
game1.startGame(p2);
game1.startGame(p3);
}
}
class GuessGame {
void startGame(Player p) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
p.guess(n);
}
}
class Player {
private int number;
Player() {
number = (int) Math.random();
}
void guess(int n) {
if (number == n) {
System.out.println("the correct answer");
} else {
System.out.println("the wrong answer");
}
}
}
添加回答
舉報