Discuss / Java / 作业

作业

Topic source

代码不能正确生成随机数,每次都是1

package com.itranswarp.learnjava;

import java.util.Scanner;

/**
 * switch实现石头/剪子/布并判断胜负
*/
public class Main {

	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 scanner = new Scanner(System.in); 
		int choice =scanner.nextInt();		
		if (choice<1 || choice>3){
			System.out.println("输入错误");
		} 
		
		int random = 1 + (int) Math.random() * 3;
		System.out.println(random);
		
		switch (choice) {
		case 1->{
		if (random ==1 ) {
			System.out.println("打平");}
			else if (random == 2) {
				System.out.println("赢了");
			}
				else {
					System.out.println("输了");
				}
				}
		case 2->{
			if (random ==1 ) {
				System.out.println("输了");}
				else if (random == 2) {
					System.out.println("平了");
				}
					else {
						System.out.println("赢了");
					}
					}
		case 3->{
			if (random ==1 ) {
				System.out.println("赢了");}
				else if (random == 2) {
					System.out.println("输了");
				}
					else {
						System.out.println("平了");
					}
					}
			}
		}
		
		
		}
		
	

	

int random = 1 + (int) (Math.random() * 3);

加上括号就能正确生成随机数了!


  • 1

Reply