Head First Java 猜数游戏

首先,编辑三个文件

GameLauncher.java

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

Player.java

public class Player {
    int number = 0;
    
    public void guess() {
	number = (int)(Math.random()*10);
	System.out.println("I'm guessing " + number);
    }
}

GuessGame.java

public 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("Number 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 got is right ? " + p1isRight);
		System.out.println("Player two got is right ? " + p2isRight);
		System.out.println("Player three got is right ? " + p3isRight);
		System.out.println("Game is over.");
		break;
	    } else {
		System.out.println("Players will have to try again.");
	    }
	}
    }
}



然后执行 javac GameLauncher.java GuessGame.java Player.java

要放在一起执行,分开执行会报错的

生成了三个.class的文件

然后 java -classpath . GameLauncher

就可以执行程序了

如果不指定 -classpath . 就不会成功,会说有的类找不到的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值