java关于在其他类中调用属性

时间:2019-03-01 09:20:19

标签: java

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

类中

如何修复错误?对不起,我英语不好。

3 个答案:

答案 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),因为p1GuessGame而不是GameLauncher的实例字段。

答案 2 :(得分:0)

如果要运行代码:

  • 将main()方法放在公共类中
  • 使用。用于访问GuessGame属性的运算符。

如果您希望自己的代码更好:

  • 在GuessGame中更改访问修饰符:public-> private,并使用getter / setter进行访问。
  • 使用if / else表达式作为guess()方法。

公共类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");
        }
    }
}