class GameLauncher{
public static void main(String[] args){
GuessGame Game1 = new GuessGame();
Game1.startGame(p1);
Game1.startGame(p2);
Game1.startGame(p3);
}
}
public class GuessGame {
public Player p1 = new Player();
public Player p2 = new Player();
public Player p3 = new Player();
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");
}
}
我的代码有误: Game1.startGame(p1); Game1.startGame(p2); Game1.startGame(p3);
编译器表示找不到 p1,p2,p3 的符号,但是我已经初始化了 Player 在 GuessGame
类中如何修复错误?对不起,我英语不好。
答案 0 :(得分:1)
p1,p2和p3在GuessGame类中声明,因此GameLauncher方法无法看到它们。您应该将这些变量设为全局变量,或者在GuessGame不使用它们的情况下在GameLauncher中声明它们。
使用代码进行编辑:
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");
}
}
答案 1 :(得分:0)
您必须使用Game1.startGame(Game1.p1)
,因为p1
是GuessGame
而不是GameLauncher
的实例字段。
答案 2 :(得分:0)
如果要运行代码:
如果您希望自己的代码更好:
公共类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");
}
}
}