1

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);
            };              
}}}
user1794625
  • 107
  • 2
  • 2
  • 9

3 Answers3

6

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

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);
Laurent S.
  • 6,816
  • 2
  • 28
  • 40
1

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 + " ");
        }

    }              
}
lrnzcig
  • 3,868
  • 4
  • 36
  • 50
Krogers122
  • 11
  • 2
  • For java7 and above it is best to use `ThreadLocalRandom`. Take a look e.g. [here](http://stackoverflow.com/a/363692/3519000) – lrnzcig Dec 17 '16 at 20:05