Discuss / Java / 为什么random出来的值一直是1

为什么random出来的值一直是1

Topic source

KarryZY正奕

#1 Created at ... [Delete] [Delete and Lock User]

如题,代码随机出来的都是石头(1),意思是只要出剪刀(2)就一定输出石头(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);
		System.out.print("Your choice :");
		int choice = scanner.nextInt();
		
		// 计算机随机数 1, 2, 3:
		int random = 1 + (int) Math.random() * 3;
		switch (choice) {
		
		// TODO:
		case 1 :
			System.out.println("Computer choose: " + random);
			System.out.println();
			if (random == 1) {
				System.out.println("Due");
			}else if (random == 2) {
				System.out.println("You Win");
			}else if (random == 3) {
				System.out.println("You Lose");
			}
			break;
		case 2 :
			System.out.println("Computer choose: " + random);
			System.out.println();
			if (random == 1) {
				System.out.println("You Lose");
			}else if (random == 2) {
				System.out.println("Due");
			}else if (random == 3) {
				System.out.println("You Win");
			}
			break;
		case 3 :
			System.out.println("Computer choose: " + random);
			System.out.println();
			if (random == 1) {
				System.out.println("You Win");
			}else if (random == 2) {
				System.out.println("You Lose");
			}else if (random == 3) {
				System.out.println("Due");
			}
			break;
		default :
			System.out.println();
			System.out.println("This is a wrong section.");
		}
	}

}

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]
int random = 1 + (int) Math.random() * 3;

->

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

  • 1

Reply