刚开始看了上面很多人写的,发现各种情况都有,最后根据廖老师留下的代码,再未改动他的代码下,利用2层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); } } }
Sign in to make a reply
明明love0
刚开始看了上面很多人写的,发现各种情况都有,最后根据廖老师留下的代码,再未改动他的代码下,利用2层case嵌套循环完成了此题。