0

I am trying to write a program in Java that asks the user how many random numbers to generate (0-999) Then the program is supposed to fill an array up with the random numbers and present them to the user.

This is what I got so far:

import java.util.*;

public class random2
{
public static void main ( String[] args )
{
    Random random;
    int i;
    int[] numbers;
    int numberOfNumbers=0;
    int upperRange=999;
    int lowerRange=0;
    int randomNumber=0;

    Scanner in = new Scanner(System.in);

    System.out.println("How many random numbers between 0-999?");
    numberOfNumbers=in.nextInt();
    numbers = new int [numberOfNumbers];


    random = new Random();

    for (i = 0; i < numberOfNumbers; i++){

    randomNumber = random.nextInt(upperRange-lowerRange) + lowerRange;
    numbers[i] = randomNumber;

    if (i==numberOfNumbers) 

    System.out.println(randomNumber);


    }      


  }

}

But the program won't present the list of the random numbers. It just exits. What did I do wrong?

Emil
  • 21
  • 5
  • 1
    In your loop, `i` will never equal `numberOfNumbers` (your loop condition is `i < numberOfNumbers`). Print the array after the loop. – Elliott Frisch Apr 03 '16 at 15:42
  • Am voting to open the re-question since the reason of not working is related to the logic in this condition *if (i==numberOfNumbers) * and nothing to do with how arrays must be printed. – ΦXocę 웃 Пepeúpa ツ Apr 03 '16 at 15:46
  • Thanks @ElliottFrisch but when I try to print the array after the loop, it only presents 1 random number. I will check out the link on arrays. – Emil Apr 03 '16 at 15:58
  • Print `numbers` (the array), not `randomNumber` (**one** random number). – Elliott Frisch Apr 03 '16 at 16:11
  • Your loop exits before `i==numberOfNumbers` becomes true. Some people use code indentation for a reason. – mustaccio Apr 03 '16 at 16:19
  • I tried that @ElliottFrisch but then the program prints "These are the random numbers: I@1b84c92" – Emil Apr 03 '16 at 16:59

0 Answers0