原理:
你输入一个数
再利用Random产生一个随机数
使用case两层嵌套循环输出:
一个判断小游戏!
看不懂的可留言交流!
package com.itranswarp.learnjava;
import java.util.Scanner;
/**
* switch实现石头/剪子/布并判断胜负
*/
public class Main {
@SuppressWarnings("preview")
public static void main(String[] args) {
System.out.println("please choice:");
System.out.println(" 1: Rock(石头)");
System.out.println(" 2: Scissors(剪刀)");
System.out.println(" 3: Paper(布)");
// 用户输入:
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
sc.close();
// 计算机随机数 1, 2, 3:
int random = 1 + (int) Math.random() * 3;
// Math.random() * 3产生一个大于等于0小于3的随机数
System.out.printf("The computer choice is:%d\n", random);
switch (choice) {
case 1 -> {
switch (random) {
case 1 -> System.out.println("平局!");
case 2 -> System.out.println("你赢了!");
case 3 -> System.out.println("你输了!");
default -> throw new IllegalArgumentException("Unexpected value: " + random);
}
}
case 2 -> {
switch (random) {
case 1 -> System.out.println("你输了!");
case 2 -> System.out.println("平局");
case 3 -> System.out.println("你赢了!");
default -> throw new IllegalArgumentException("Unexpected value: " + random);
}
}
case 3 -> {
switch (random) {
case 1 -> System.out.println("你赢了!");
case 2 -> System.out.println("你输了!");
case 3 -> System.out.println("平局");
default -> throw new IllegalArgumentException("Unexpected value: " + random);
}
}
default -> throw new IllegalArgumentException("Unexpected value: " + choice);
}
}
}