前言
Random类的简单使用
.nextInt()方法,返回伪随机的,均匀分布 int值介于0(含)和指定值(不包括),从该随机数生成器的序列绘制。
public class Demo_02 {//出拳游戏:1表示石头,2表示剪刀,3表示布// 接收用户输入的拳 并输出 ,然后电脑随机产生一个数 对比输赢// 欢迎来到游戏中心// 请用户出拳(1表示石头,2表示剪刀,3表示布)public static void main(String[] args) {Scanner info = new Scanner(System.in);Random random = new Random();String[] s = new String[]{"石头", "剪刀", "布"};while (true) {System.out.println("1表示石头,2表示剪刀,3表示布");System.out.print("player:");int user = info.nextInt();//nextInt()方法,返回伪随机的,均匀分布 int值介于0(含)和指定值(不包括)int npc = random.nextInt(3)+1;System.out.println("npc:"+npc);switch(user){case 1:System.out.println(s[user]+"VS"+s[npc-1]);if (npc == 1){System.out.println("平局");}else if (npc == 2){System.out.println("玩家获胜");}else if (npc == 3){System.out.println("电脑获胜");}break;case 2:System.out.println(s[user]+"VS"+s[npc-1]);if (npc == 2){System.out.println("平局");}else if (npc == 3){System.out.println("玩家获胜");}else if (npc == 1){System.out.println("电脑获胜");}break;case 3:System.out.println(s[user]+"VS"+s[npc-1]);if (npc == 3){System.out.println("平局");}else if (npc == 1){System.out.println("玩家获胜");}else if (npc == 2){System.out.println("电脑获胜");}break;default:System.out.println("年轻人不讲武德,我劝你耗子尾汁");break;}}}
}
运行结果
2023-01-09修改,隔了这么久才改。汗!就把错误保留下对比看看。感谢指出错误的小伙伴。
public class Demo_02 {//出拳游戏:1表示石头,2表示剪刀,3表示布// 接收用户输入的拳 并输出 ,然后电脑随机产生一个数 对比输赢// 欢迎来到游戏中心// 请用户出拳(1表示石头,2表示剪刀,3表示布)public static void main(String[] args) {Scanner info = new Scanner(System.in);Random random = new Random();String[] s = new String[]{"石头", "剪刀", "布"};while (true) {System.out.println("=========================猜拳游戏============================");System.out.println("1表示石头,2表示剪刀,3表示布");System.out.print("player:");try {int user = info.nextInt();info.nextLine();//nextInt()方法,返回伪随机的,均匀分布 int值介于0(含)和指定值(不包括)int npc = random.nextInt(3)+1;System.out.println("npc:"+npc);switch(user){case 1:System.out.println(s[user-1]+"VS"+s[npc-1]);if (npc == 1){System.out.println("平局");}else if (npc == 2){System.out.println("玩家获胜");}else if (npc == 3){System.out.println("电脑获胜");}break;case 2:System.out.println(s[user-1]+"VS"+s[npc-1]);if (npc == 2){System.out.println("平局");}else if (npc == 3){System.out.println("玩家获胜");}else if (npc == 1){System.out.println("电脑获胜");}break;case 3:System.out.println(s[user-1]+"VS"+s[npc-1]);if (npc == 3){System.out.println("平局");}else if (npc == 1){System.out.println("玩家获胜");}else if (npc == 2){System.out.println("电脑获胜");}break;default:System.out.println("年轻人不讲武德,我劝你耗子尾汁");break;}}catch (Exception e){System.out.println(e.getMessage());info.next();System.out.println("请重新输入");}}}
}