(游戏:剪刀、石头、布)编写可以玩流行的剪刀-石头-布游戏的程序。 (剪刀可以剪布,石头 可以砸剪刀,而布可以包石头。 )程序提示用户随机产生一个数,这个数为 0、1或者 2, 分别表 示石头、剪刀和布。程序提示用户输入值 0、1或者 2, 然后显示一条消息,表明用户和计算机 谁贏了游戏,谁输了游戏,或是打成平手。下面是运行示例:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int user=0;
boolean flag = true;
// 第四个剪刀用于减少输出逻辑嵌套层数
String[] str = {"剪刀","石头","布","剪刀"};
// 防呆
while (flag) {
System.out.print(str[0]+"(0),"+str[1]+"(1),"+str[0]+"(2):");
// 用户出拳
user = sc.nextInt();
if (user > -1 && user < 3) {
flag = false;
}else{
System.out.println("数据非法,请重新输入:");
}
}
sc.close();
// pc出拳
int pc = (int) (Math.random() * 3);
// 猜拳逻辑
if (user == pc) {
System.out.println("电脑出的是"+str[user]+",你出的是"+str[user]+",平局");
}
else if (user == pc + 1 || user == pc - 2) {
System.out.println("电脑出的是"+str[user]+",你出的是"+str[user+1]+",你赢了");
}
else if (user + 1 == pc || user - 2 == pc) {
System.out.println("电脑出的是"+str[user+1]+",你出的是"+str[user]+",你输了");
}
}
public class Test {
public static void main(String[] args){
//程序说明:剪刀石头布
//计算机随机出一个
int c = (int)(Math.random() * 3);
//提示用户出一个
System.out.println("scissor(0),rock(1),paper(2):");
Scanner input = new Scanner(System.in);
int y = input.nextInt();
if(y != 0 && y != 1 && y != 2){
System.out.println("error input");
return;
}
//给出结果
if(c == y){
if(c == 0)
System.out.println("The computer is scissor.You are scissor too.It is a draw");
if(c == 1)
System.out.println("The computer is rock.You are rock too.It is a draw");
if(c == 2)
System.out.println("The computer is paper.You are paper too.It is a draw");
}
else if(c == 0){
if(y == 1)
System.out.println("The computer is scissor.You are rock.You win");
if(y == 2)
System.out.println("The computer is scissor.You are paper.You lose");
}
else if(c == 1)
{
if(y == 0)
System.out.println("The computer is rock.You are scissor.You lose");
if(y == 2)
System.out.println("The computer is rock.You are paper.You win");
}
else
{
if(y == 0)
System.out.println("The computer is paper.You are scissor.You win");
if(y == 1)
System.out.println("The computer is paper.You are rock.You lose");
}
}
}