- Java code
import java.io.*;import java.util.*;public class AnimalFight { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub while (true) { System.out.println("斗兽棋,大象吃狮子,狮子吃老虎,老虎吃狼,狼吃狗,狗吃猫,猫吃老鼠,老鼠吃大象" + "\r\n大象(7),狮子(6),老虎(5),狼(4),狗(3),猫(2),老鼠(1)" + "\t退出(0)"); BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); try { int player = Integer.parseInt(br.readLine()); if (player == 0)// 退出 { break; } if (player < 0 || player > 7)// 非法数字 { System.out.println("没有这个动物啊!"); continue;// 跳过本次循环 } Random rnd = new Random(); int computer = 1 + rnd.nextInt(6);// 电脑随机出一个动物 Fight(player, computer);// 调用此方法比较并显示结果 } catch (IOException e) { System.out.println("读数据的时候出了点小错误"); continue; } catch (NumberFormatException e) { System.out.println("只能输入数字!"); continue; } } } /* * 斗兽棋,大象吃狮子,狮子吃老虎,老虎吃狼,狼吃狗,狗吃猫,猫吃老鼠,老鼠吃大象 * 大象(7),狮子(6),老虎(5),狼(4),狗(3),猫(2),老鼠(1) 退出(0) */ static void Fight(int player, int computer) {// 将玩家和电脑的数值传进来比较 if (player == 1 && computer == 7)// 玩家出老鼠,电脑出大象 { System.out.println("你出的是老鼠,电脑出的是大象,你赢了"); } else if (player == 7 && computer == 1)// 玩家出大象,电脑出老鼠 { System.out.println("你出的是大象,电脑出的是老鼠,你输了"); } else {// 其他情况 if (player == computer) {// 相等 System.out.println("你出的是:" + Result(player) + ",电脑出的是:" + Result(computer) + ",平手"); } else if (player > computer) {// 玩家大于电脑 System.out.println("你出的是:" + Result(player) + ",电脑出的是:" + Result(computer) + ",你赢了"); } else {// 玩家小于电脑 System.out.println("你出的是:" + Result(player) + ",电脑出的是:" + Result(computer) + ",你输了"); } } System.out.println(); } static String Result(int animal)// 显示出的是什么动物,应该还有更好的办法减少代码,刚学java,不懂 { String animalName = ""; if (animal == 1) { animalName = "老鼠"; } else if (animal == 2) { animalName = "猫"; } else if (animal == 3) { animalName = "狗"; } else if (animal == 4) { animalName = "狼"; } else if (animal == 5) { animalName = "老虎"; } else if (animal == 6) { animalName = "狮子"; } else if (animal == 7) { animalName = "大象"; } return animalName; }}//帮改一下Result方法吧!谢谢!
------解决方案--------------------
static String Result(int animal)// 显示出的是什么动物
{
String animalName[] = {"老鼠","猫", "狗","狼", "老虎","狮子","大象"};
return animalName[animal - 1];
}
}