方法一:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("剪刀石头布小游戏");
System.out.println("-----------------------------------");
Scanner input = new Scanner(System.in);
int gamer;
int computer;
boolean flag = true;
String yn = "Y";
while (flag) {
System.out.println("请输入:(1.石头、2.剪刀 、3.布 )");
gamer = input.nextInt();
computer = (int) (Math.random() * 3) + 1;
System.out.print("结果为:");
if (gamer == 1) {
flag = false;
if (computer == 1) {
System.out.print("平局。" + "\n你出的石头,电脑出的石头");
} else if (computer == 0)
System.out.print("你获胜了!" + "\n你出的石头,电脑出的剪刀");
else
System.out.print("电脑获胜了。" + "\n你出的石头,电脑出的布");
} else if (gamer == 2) {
flag = false;
if (computer == 2)
System.out.print("平局" + "\n你出的剪刀,电脑出的剪刀");
else if (computer == 3)
System.out.print("你获胜了!" + "\n你出的剪刀,电脑出的布");
else
System.out.print("电脑获胜了" + "\n你出的剪刀,电脑出的石头");
} else if (gamer == 3) {
flag = false;
if (computer == 3)
System.out.print("平局" + "\n你出的布,电脑出的布");
else if (computer == 1)
System.out.print("你获胜了!" + "\n你出的布,电脑出的石头");
else
System.out.print("电脑获胜了" + "\n你出的布,电脑出的剪刀");
} else {
System.out.println("错误,请重新输入");
flag = true;
}
if (flag == false) {
System.out.println("\n是否继续进行:(Y/N)");
yn = input.next();
if ("y".equalsIgnoreCase(yn)) {
flag = true;
} else
System.out.println("游戏结束!");
}
}
}
}
Random r=new Random();
int computer = r.nextInt(3)+1;
String str = "AbCd";
char c = str.charAt(0);
另一种方式:
因为第一个 if-else if-else多选结构太过麻烦,很多都是重复内容,进行一些改进。
import java.util.Scanner;
public class Game2 {
public static void main(String[] args) {
System.out.println("剪刀石头布小游戏");
System.out.println("-----------------------------------");
Scanner input = new Scanner(System.in);
int gamer = 0;
int computer = 0;
boolean flag = true;
String strGamer = "布";
String strComputer = "布";
String yn = "Y";
while (flag) {
System.out.println("请输入:(1.石头、2.剪刀 、3.布 )");
gamer = input.nextInt();
computer = (int) (Math.random() * 3) + 1;
switch (gamer) {
case 1:strGamer = "石头";break;
case 2:strGamer = "剪刀";break;
case 3:strGamer = "布";break;
}
switch (computer) {
case 1:strComputer = "石头";break;
case 2:strComputer = "剪刀";break;
case 3:strComputer = "布";break;
}
System.out.print("结果:");
if (computer == gamer) {
System.out.print("平局" + "\n" + "电脑出的是" + strComputer + ",你出的是" + strGamer);
flag = false;
}
if (computer == 1 && gamer == 2 || computer == 2 && gamer == 3 || computer == 3 && gamer == 1) {
System.out.println( "你赢了" + "\n" + "电脑出的是" + strComputer + ",你出的是" + strGamer);
flag = false;
}
if (computer == 1 && gamer == 3 || computer == 2 && gamer == 1 || computer == 3 && gamer == 2) {
System.out.println("电脑赢了" + "\n" + "电脑出的是" + strComputer + ",你出的是" + strGamer);
flag = false;
}
if (gamer != 1 && gamer != 2 && gamer != 3) {
System.out.println("错误" + "\n" + "只能输入1、2、3");
flag = true;
}
if (flag == false) {
System.out.println("\n是否继续进行:(Y/N)");
yn = input.next();
if ("y".equalsIgnoreCase(yn)) {
flag = true;
} else
System.out.println("游戏结束!");
}
}
}
}