SkyVar
SkyVar

Reputation: 351

Why doesn't my number record and print in my array?

Ok so I'm trying to make a pretty simple number generator with limits of 1 and 100. I've read over everything I can find online and can't figure out why my code doesn't record the numbers between 1-100 in the array then print the numbers from the array. When I run the code the number 36 gets printed over and over. What am I doing wrong?

import java.util.Random;
public class NumberGen
{
    public static void main(String[] args)
    {
        int numbers[]=new int[10];
        Random gen = new Random();

        for(int i=0; i<numbers.length;i++)
        {
            int number=gen.nextInt();
            while(number<1 || number>100)
            {
                number=gen.nextInt();
            }

            while(number<=100 && number >=1)
            {
                numbers[i]=number;
                System.out.println(numbers[i]);
            }


        }


    }

}

Upvotes: 1

Views: 86

Answers (3)

SGM1
SGM1

Reputation: 978

Consider what is happening here:

   for(int i=0; i<numbers.length;i++)
    {
        /**
        *int number=gen.nextInt();
        *while(number<1 || number>100)
        *{
        *    number=gen.nextInt();
        *}
        **/
        number = 1;

        while(number<=100 && number >=1)
        {
            numbers[i]=number;
            System.out.println(numbers[i]);
        }
    }

The while in the for loop is stuck in an infinite loop since 'number' never changes

What you should be trying to do is store the number in a single for/while loop then print in a seperate for/while loop

for(int i=0; i<numbers.length;i++){
    //FYI gen.nextInt(100) generates a int from 0 to 99
    //store values
}
for(int i=0; i<numbers.length;i++){
    //print values in arr
}

Upvotes: 0

Alli K
Alli K

Reputation: 81

Shouldn't the second while be an if? I'm pretty sure it's an infinite loop. And why are you using the first while, well all of:

int number=gen.nextInt();
            while(number<1 || number>100)
            {
                number=gen.nextInt();
            }

when you could just int number=gen.nextInt(100)+1;

Upvotes: 3

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

You should use another flavor of nextInt -> http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)

In your case:

int number=gen.nextInt( 100 ) + 1;

Upvotes: 2

Related Questions