0

Here's my method:

public int randomIntegers() {
    array = new int[20];
    Random r = new Random();

    for(i =0; i<20; i++) {
        int intRandom = r.nextInt(1000);
        if (intRandom >= 100) {
            array[i] = intRandom;       
        }
    }
    return array[i];
}

Println:

System.out.println(array[i]);

And when I use println in the main method, I get a NullPointerException. Have honestly tried to conceptually understand why this isn't working, to no avail.

4
  • 1
    Show us what are you trying to print, or your main method and also define the values of size , max and min Commented Oct 4, 2014 at 3:22
  • And you are returning the last element of the array if you want to return complete array then return the reference Commented Oct 4, 2014 at 3:26
  • Try to print the value of i before printing. And also - are you initializing the array before calling the print statement? Commented Oct 4, 2014 at 3:35
  • Where is i declared? I think you need to show the whole file. Commented Oct 4, 2014 at 4:32

2 Answers 2

3

You are trying to return an integer, not the entire array. The integer is not even valid because you are trying to return the integer after the last integer in the array.

I'm guessing you want to return the entire array to your main method, if so you need to change the method signature to return an array, and change the return statement, as such:

public int[] randomIntegers() {
   //code....
   return array;
}

On another note, you don't always fill your array with generated integers. A slot will, when the random number generated is < 100 (so about every tenth time), not be filled and thus have a value of 0 in the slot of the int.

Sign up to request clarification or add additional context in comments.

1 Comment

primitive default will be set - 0 in case if is not satisfied. Please correct me if I am not.
0

If the code in your question is a true reflection of the code you are actually running, then the only plausible explanations for

     System.out.println(array[i]);

throwing an NPE are:

  • You haven't called randomIntegers() (yet).
  • The array you are printing is a different variable to the array that you are assigning to in the randomIntegers method.

If that doesn't explain things, please update your question with your entire program and the stacktrace.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.