I have been stuck for about an hour and after googling and doing research I could't get my code to run. It shows not a single error and when I press run it just opens debug and does nothing. I am using eclipse. I am trying to create a list of 10 objects and to give them random numbers.
class test {
public static void main(String[] args){
int a [] = new int[9];{
for (int i = 0; i < a.length; i++)
a[i] = a[(int)(Math.random()*70+15)];
for (int elem : a){
System.out.println(elem);
};
}}}
-
1indenting, and not having random curly-brace blocks make code easier to readSam I am says Reinstate Monica– Sam I am says Reinstate Monica2013年03月19日 16:18:49 +00:00Commented Mar 19, 2013 at 16:18
3 Answers 3
If you are actually launching the application, it should fail with an exception at the following line:
a[i] = a[(int)(Math.random()*70+15)];
Here, a[] consists of nine elements, so its highest index is 8. However, Math.random()*70+15 is guaranteed to generate numbers that are greater than 8.
5 Comments
+15 makes this fail every single time.I don't know any Java, but I would say :
for (int i = 0; i < a.length; i++)
a[2] = a[(int)(Math.random()*70+15)];
should be
for (int i = 0; i < a.length; i++)
a[i] = (int)(Math.random()*70+15);
Comments
I would suggest using the Random number generator instead. I would also suggest using better names than i or a for your programs.
import java.util.Random;
class test {
public static void main(String[] args){
Random object = new Random ();//declare for your object
int a; //declare your integer type (I would suggest
// changing that to be more descriptive)
for (int i = 1; i <=10; i++)
{
a = object.nextInt(100); // change 100 to however large
// parameter you want
System.out.println(a + " ");
}
}
}