楼主为了完成作业,花了一小会时间自己琢磨了一下,写出了这个石头剪刀布的小游戏。
思路很简单,就是令石头=2,剪刀=1,布=0,那么电脑随机生成一个数,分别去对应,游戏者同时也输入一个数字,也是对应着前面的石头=2,剪刀=1,布=0。再进行比较,最后用一个flag变量去标记一下是赢了、输了、还是平局,就可以了。
下面是我写的代码,我的水平很垃圾,比不上很多大佬,因此仅供参考:
import java.util.Scanner;//石头剪刀布的游戏
public class homework_3_9 {
public static void main(String[] args){
int gesture = (int) (Math.random()*3);
int you_input;
int flag = 3;
String what = "",you_what = "",flag_result = "";
switch(gesture){
case 0: what = "布";break;
case 1: what = "剪刀";break;
case 2: what = "石头";break;
}
System.out.println("你出什么?(石头(2)、剪刀(1)、布(0)):");
Scanner input = new Scanner(System.in);
you_input = input.nextInt();
while(you_input > 2 || you_input < 0){
System.out.print("输入错误,请重新输入:");
you_input = input.nextInt();
}
switch(you_input){
case 0: you_what = "布";break;
case 1: you_what = "剪刀";break;
case 2: you_what = "石头";break;
}
//判断石头剪刀布的胜负关系
if(gesture > you_input ){
if(gesture == 2 && you_input == 0){
flag = 1;
}
else flag = 0;
}
else if(gesture < you_input) {
if(gesture == 0 && you_input ==2){
flag = 0;
}
else flag = 1;
}
else if(gesture == you_input){
flag = 2;
}
switch(flag){
case 0: flag_result = "输";break;
case 1: flag_result = "赢";break;
case 2: flag_result = "平局";break;
}
System.out.print("计算机出的是:"+what+","+"你出"+you_what+","+"你"+flag_result+"了。");
}
}