Discuss / Java / 剪刀石头布作业---双层switch表达式嵌套

剪刀石头布作业---双层switch表达式嵌套

Topic source

每个switch语句块结束一定要加 ;  不然会出出现 fall through 的问题

之前没加;找了半天不知道问题在哪里

System.out.println("please choice:");
		System.out.println(" 1: 石头");
		System.out.println(" 2: 剪刀");
		System.out.println(" 3: 布");
		
		
		Scanner scanner = new Scanner(System.in); // 创建Scanner对象
		System.out.print("Input your choice: "); // 打印提示
		int choice = scanner.nextInt(); // 读取一行输入并获取字符串
		
		if (choice<1 || choice>3) {
			System.out.println("wrong choice");
		}
		
		// 计算机随机数 1, 2, 3:
		int random = 1 + (int) Math.random() * 3;
		System.out.println("Random Number:"+random);
		
		
		switch (choice) {
		case 1 ->{
			switch (random) {
			case 1 -> System.out.println("平手");
			case 2 -> System.out.println("You win");
			case 3 -> System.out.println("You lose");
			
			default -> System.out.println("default");};
			}
		
		case 2 ->{
			switch (random) {
			case 1 -> System.out.println("You lose");
			case 2 -> System.out.println("平手");
			case 3 -> System.out.println("You Win");
			
			default -> System.out.println("default");};
			}
		
		case 3 ->{
			switch (random) {
			case 1 -> System.out.println("You Win");
			case 2 -> System.out.println("You lose");
			case 3 -> System.out.println("平手");
			
			default -> System.out.println("default");};
		}

		default -> System.out.println("Default");
		};

  • 1

Reply