Discuss / Java / 老师代码上随机数只能生成1

老师代码上随机数只能生成1

Topic source

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

顺序是先整数,再x3,1+0*3,只有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");
		// 用户输入:
		int choice = 0;
		Scanner scanner = new Scanner(System.in);
		choice = scanner.nextInt();
		// 计算机随机数 1, 2, 3:
//		int random = (int) (1+Math.random() * 3);
		int random = 1+ (int)(Math.random()*3);
		switch (choice) {
		// TODO:
		case 1:{
			System.out.println("your choice is Rock");
			switch (random) {
			case 1:
				System.out.println("平局");
				break;
			case 2:
				System.out.println("你赢了");
				break;
			case 3:
				System.out.println("你输了");
				break;
			}
			break;
		}
		case 2:{
			System.out.println("your choice is Scissors");
			switch (random) {
			case 1:
				System.out.println("你输了");
				break;
			case 2:
				System.out.println("平局");
				break;
			case 3:
				System.out.println("你赢了");
				break;
		}
			break;
		}
		case 3:{
			System.out.println("your choice is Paper");
			switch (random) {
			case 1:
				System.out.println("你赢了");
				break;
			case 2:
				System.out.println("你输了");
				break;
			case 3:
				System.out.println("平局");
				break;
		}
			break;
	}
		}
	}
}
	

  • 1

Reply