案例介绍:
编写程序:模拟石头剪刀布游戏。程序在0、1或2中随机产生一个数,0代表布、1代表剪刀、2代表石头。提示用户输入值2、1、0,然后显示一条信息,表明用户与计算机谁赢得了比赛。
案例代码:
import java.util.Scanner;
public class Game {
public static void main(String[] args){
int comp =(int)( Math. random() * 3);
int your;
Scanner input = new Scanner( System.in);
System.out. print("你出什么?(石头(2)、剪刀(1)、布(0)):");
your =input.nextInt();
System. out. print("计算机出的是:" +
((comp==2)?"石头":((comp == 1)?"剪刀":"布")));
System. out. print(",你出" +
(( your == 2)?"石头":((your == 1)?"剪刀": "布")));
if( comp == your){
System. out. print(",平局");
}else
if(( your - comp ==1 || your - comp == -2)){
System.out.print(",你赢了!");
}else{
System. out. print(",你输了!");
}
}
}
案例运行图: