Filling array with 10 random values
For the life of me I cannot understand why this code does not fill the array with random values. I would really appreciate any help.
Code:
import java.util.Random;
public class test
{ public static void main (String[] args)
{ int[] num = new int[10];
Random generator = new Random();
for (int i=0;i>10;i++)
{ num[i]=generator.nextInt(50)+1;
System.out.println(num[i]); //this should be outputing the values of num[] but it is not??
}
}
}
Re: Filling array with 10 random values
Check your for loop conditions, the middle one may be wrong. :o:
Re: Filling array with 10 random values
Quote:
Originally Posted by
quinnvanorder
For the life of me I cannot understand why this code does not fill the array with random values. I would really appreciate any help.
Code:
for (int i=0;i>10;i++)
Just to spare your life haha the for loop you got the < backwards you are telling it to continue until i is not > 10 but i = 0 is not greater than 10 so it never starts.
Re: Filling array with 10 random values
I originally had it as i>num.length, and it was not working, thus I changed it to i>10 and it is still not working :(
Re: Filling array with 10 random values
Quote:
Originally Posted by
romero4742
Just to spare your life haha the for loop you got the < backwards you are telling it to continue until i is not > 10 but i = 0 is not greater than 10 so it never starts.
oh... of course *smacks forehead* thanks man
Re: Filling array with 10 random values
romero stated literally what I was trying to get you to discover on your own...
Re: Filling array with 10 random values
Also, you should fix your code formatting. Don't start code on the same line as an opening bracket, and use a little more whitespace to improve readability. Also, you will want to follow Java naming rules with your class names starting with capital letters and method and variable names with lower-case letters. So for instance, your code may want to look like...
Code:
import java.util.Random;
public class Test {
public static void main(String[] args) {
int[] num = new int[10];
Random generator = new Random();
for (int i = 0; i < 10; i++) {
num[i] = generator.nextInt(50) + 1;
System.out.println(num[i]);
}
}
}
This may seem trivial, and perhaps with your small program it is, but it becomes very important when you are trying to get others to understand larger more complex programs. So it's better to start good habits now.