简体   繁体   English

Math.random在代码中无法正常工作

[英]Math.random not properly working in the code

package arrays;
import java.util.Scanner;

public class Raffle {
    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        System.out.println("Enter the number of partcipants ");
        int no=scan.nextInt();
        String participants[]=new String[no];
        System.out.println("Please enter their names and check out the random winner");
        for(int i=0;i<no;i++) {
            participants[i]=scan.next();
        }
        int rand=(int)Math.random()*no;
        System.out.println(rand);
        System.out.println("The winner of the raffle is "+participants[rand]);
    }
}

I used Math.random() but I see during run that always the 0 index position is giving the result and not the random value. 我使用了Math.random()但在运行过程中看到总是0索引位置给出结果,而不是随机值。 Any suggestions? 有什么建议么? I am on eclipse oxygen. 我正在食蚀性氧气。

You are casting the result of Math.random() to int prior to multiplying it by no , which results in 0 , since Math.random() < 1.0 . 您将Math.random()的结果强制转换为int然后再乘以no ,结果为0 ,因为Math.random() < 1.0

Change 更改

int rand=(int)Math.random()*no;

to

int rand=(int)(Math.random()*no);

Casting a double between 0.0 (inclusive) and 1.0 (exclusive) will always round down to zero. 在0.0(含)和1.0(不含)之间转换一个双精度值将始终舍入为零。 A Math.random() value should first be multiplied with some factor before casting it to an int to get a value between zero (inclusive) and the multiplication factor (exclusive). 在将Math.random()值转换为int值之前,应先将其与某个因子相乘,以得到介于零(含)和乘法因子(不含)之间的值。 Another possible solution would be to use the nextInt() method of java.util.Random. 另一种可能的解决方案是使用java.util.Random的nextInt()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM