Reputation: 351
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
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
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
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