当前位置: 代码迷 >> J2SE >> random类的练习题解决办法
  详细解决方案

random类的练习题解决办法

热度:90   发布时间:2016-04-24 13:18:27.0
random类的练习题
编制一个剪子、包袱、锤游戏程序。计算机的选择由随机数发生器实现。
运行结果提示:
开始游戏
剪子(1);锤(2),包袱(3)中,选择哪一个?1
<结果>
玩家:剪子
计算机:包袱
玩家胜
比分:1:0
继续游戏吗?[y/n] y
........

------解决方案--------------------
public class Main {

private int com = 0; //电脑胜的次数
private int people = 0; //人胜的次数

/** Creates a new instance of Main */
public Main() {
com = 0;
people = 0;
}

public void setCom(int com) {
this.com = com;
}

public int getCom() {
return this.com;
}

public void setPeople(int people) {
this.people = people;
}

public int getPeople() {
return this.people;
}

public static void main(String[] args) throws IOException {
// TODO code application logic here
Main game = new Main();
int comChose = 0; //电脑出的
int chose = 0; //人出的
String again = null; //是否再来
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random rdm = new Random();

System.out.println("开始游戏");
do {
System.out.println("剪子(1);锤(2),包袱(3)中,选择哪一个?");

chose = Integer.parseInt(br.readLine()); 
//显示选择结果
System.out.println("\n<结果>");
System.out.println("玩家" + game.choseWhich(chose));
comChose = rdm.nextInt(2) + 1;
System.out.println("计算机" + game.choseWhich(chose));
//-----------
//计分
if(chose > comChose) {
System.out.println("玩家胜");
game.setPeople(game.getPeople() + 1);
}else if(chose < comChose) {
System.out.println("电脑胜");
game.setCom(game.getCom() + 1);
}else {
System.out.println("平局");
}
//-----------
System.out.println("比分:" + game.getPeople() + ":" + game.getCom());
System.out.println("继续游戏吗?[y/n]");

again = br.readLine(); 

}while("y".equalsIgnoreCase(again));
}



private String choseWhich(int n) {
switch(n) {
case 1 :
return "剪子";
case 2 :
return "锤";
case 3 :
return "包袱";
default :
return null;
}
}

}
  相关解决方案