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的符号,但我已经在GuessGame类中初始化了Player


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


慕容3067478
浏览 178回答 3
3回答

海绵宝宝撒

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

慕盖茨4494581

如果你想运行代码:将您的 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");        }    }}

蓝山帝景

您必须使用Game1.startGame(Game1.p1)sincep1是GuessGameand not的实例字段GameLauncher。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java