目录
1.程序要求
写一个简单程序来实现用户与电脑玩剪刀石头布游戏,该程序先随机生成一个数字0、1或2,分别代表剪刀,石头,布。该程序提示用户输入0,1或2,如果输入错误,则提示非法输入,请重再试一次,如果通过,则并显示一条消息,告知用户和计算机得分情况,先赢了三局的一方获得总胜利。(BO5了属于是)
2.
在while循环中来实现要求,每次循环开始先设置随机函数,给电脑生成0,1或2其中一个数字,然后用Scanner类,将用户输入流保存,用一个if判断输入是否合法,再通过switch来判断用户与电脑的比赛情况,对于分数,可以设置两个变量:用户得分,电脑得分,当有一方超过2分,则结束while循环,告知最终结果。
3.
import java.util.Scanner;
public class scissor_rock_paper{
public static void main(String[] args){
int compWinN = 0;//Computer score
int peoWinN = 0;//User score
Scanner input = new Scanner(System.in);
System.out.println("************Game start!************");
while(peoWinN<=2&&compWinN<=2) {
// Computer selecting
int comp = (int) (Math.random() * 3);
// If input value is illegal
if (input.hasNextInt() == false) {
System.out.println("Your input is illegal.");
break;
}
// People selecting
int user=input.nextInt();
System.out.println("scissor (0), rock (1), paper (2):" + user);
//Judge the score
switch (user) {
case 0:
if (comp == 0) {
System.out.println("The computer is scissor. You are scissor.(computer:" + compWinN + " you:" + peoWinN + ")");
break;
} else if (comp == 1) {
compWinN++;
System.out.println("The computer is rock. You are scissor.(computer:" + compWinN + " you:" + peoWinN + ")");
break;
} else if (comp == 2) {
peoWinN++;
System.out.println("The computer is paper. You are scissor.(computer:" + compWinN + " you:" + peoWinN + ")");
break;
}
case 1:
if (comp == 0) {
peoWinN++;
System.out.println("The computer is scissor. You are rock.(computer:" + compWinN + " you:" + peoWinN + ")");
break;
} else if (comp == 1) {
System.out.println("The computer is rock. You are rock.(computer:" + compWinN + " you:" + peoWinN + ")");
break;
} else if (comp == 2) {
compWinN++;
System.out.println("The computer is paper. You are rock.(computer:" + compWinN + " you:" + peoWinN + ")");
break;
}
case 2:
if (comp == 0) {
compWinN++;
System.out.println("The computer is scissor. You are paper.(computer:" + compWinN + " you:" + peoWinN + ")");
break;
} else if (comp == 1) {
peoWinN++;
System.out.println("The computer is rock. You are paper.(computer:" + compWinN + " you:" + peoWinN + ")");
break;
} else if (comp == 2) {
System.out.println("The computer is paper. You are paper.(computer:" + compWinN + " you:" + peoWinN + ")");
break;
}
}
}
// Judge who wins the game&&Print the intermediate result
if(peoWinN > 2)
System.out.print("You won!");
else if (compWinN>2)
System.out.print("Computer won!");
else {
System.out.println("Please try again.");
}
input.close();
}
}
总结: 用了很笨但直接的方法,虽然运行结果还算满意,但是可以改进的地方还很多(笑),代码太过繁琐,不够简便,算是给各位提供一个思路吧, 大家有想分享的或是提意见,都可以在评论底下提出~