-1

I have written this code to create an array list that fills a list with 50 numbers but they all must be random numbers and no number can be the same and all numbers must be between 1 and 999. However, in my code, "randomNum" is returning only numbers between -10 and +10.

Any help on how to change this is greatly appreciated

The code I have right now:

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();
}


}
A J
  • 1,439
  • 4
  • 25
  • 42

1 Answers1

0

You need to define your Random like this:

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

So change your Code like this:

public class Main {

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();
}


}
M.Dan
  • 554
  • 1
  • 4
  • 16