(java)<name>无法解析为变量</name>

时间:2014-04-17 13:28:24

标签: java variables

我曾尝试过Head First Java第2版的猜测游戏,而我似乎无法确定导致此问题的原因。

class GuessGame {
    Player p1;
    Player p2;
    Player p3;
    public 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 0 and 9...");
        while(true){
            System.out.println("nr 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 has got it right? "+p1isRight);
                System.out.println("Player two has got it right? "+p2isRight);
                System.out.println("Player three has got it right? "+p3isRight);
                System.out.println("game over bitch");
                break;
            } else { System.out.println("player will have to try again.");
            }
        }
    }
}
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){
        GuessGame = new GuessGame();
        game.startGame();
    }
}

4 个答案:

答案 0 :(得分:2)

您需要为您的类实例提供变量名称。 game是合适的,因为您已经使用它来致电startGame

GuessGame game = new GuessGame();
          ^

答案 1 :(得分:2)

问题是你在实例化游戏时缺少变量名称:

public class GameLauncher{
    public static void main(String[] args){
        GuessGame game= new GuessGame(); //game is the variable
        game.startGame();
    }
}

答案 2 :(得分:0)

一切看起来都不错。除了一个错字之外。

没有为GuessGame创建对象,这就是你无法运行它的原因。

修改:

   GuessGame game= new GuessGame();

    game.startGame();

电流:

   GuessGame = new GuessGame();

    game.startGame();

答案 3 :(得分:0)

public class GameLauncher{
    public static void main(String[] args){
        GuessGame = new GuessGame();
        game.startGame();
    }
}

你还没有宣布&#34;游戏&#34;。它应该是:

GuessGame game = new GuessGame()
game.startGame()