【问题标题】:The program prints out numbers between -10 and +10 however i wish to have it between 1 and 999 [duplicate]该程序打印出-10到+10之间的数字但是我希望它在1到999之间[重复]
【发布时间】:2019-05-06 11:37:21
【问题描述】:

我编写了这段代码来创建一个数组列表,该列表用 50 个数字填充列表,但它们都必须是随机数,并且没有数字可以相同,所有数字都必须在 1 到 999 之间。但是,在我的代码中, "randomNum" 只返回 -10 到 +10 之间的数字。

非常感谢任何有关如何更改此设置的帮助

我现在的代码:

import java.util.Random;

public class NumberList {


private static double[] anArray;

public static double[] list(){
    anArray = new double[50];
    return anArray;
}

public static void print(){
    for(double n: anArray){
        System.out.println(n+" ");
    }
}


public static double randomFill(){
    Random rand = new Random();
    int randomNum = rand.nextInt();
    return randomNum;
}

public static void main(String args[]) {
    list();
    for(int i = 0; i < anArray.length; 
i++){
        anArray[i] = randomFill();
    }
    print();
}


}

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    你需要像这样定义你的 Random:

    Random rand=new Random();
    rand.nextInt((max+1) - min) + min;
    

    所以像这样改变你的代码:

    公共类主{

    private static int[] anArray;
    
    public static int[] list(){
        anArray = new int[50];
        return anArray;
    }
    
    public static void print(){
        for(int n: anArray){
            System.out.println(n+" ");
        }
    }
    
    
    public static int randomFill(){
        Random rand = new Random();
        int randomNum = rand.nextInt((1000) - 1) + 1;
        return randomNum;
    }
    
    public static void main(String args[]) {
        list();
        for(int i = 0; i < anArray.length; 
    i++){
            anArray[i] = randomFill();
        }
        print();
    }
    
    
    }
    

    【讨论】:

    • 我这样做了,但是我得到了这个错误 NumberList.java:22: error: not a statement rand.nextInt((max+1) - min ) + min; ^ 1 个错误
    • 你不能写 min max 你需要把它改成 1 和 999。参见上面的更改方法。
    • 这确实有效,但是有没有办法让它打印出像 789 而不是 789.0 这样的数字?
    • 是的,我编辑了我的答案。您需要使用 int 数据类型。
    • 是的,谢谢你,现在非常感谢
    猜你喜欢
    • 1970-01-01
    • 2011-04-05
    • 2013-12-21
    • 1970-01-01
    • 2014-12-09
    • 2016-04-18
    • 2013-07-28
    • 2018-11-12
    相关资源
    最近更新 更多