grizzo
grizzo

Reputation: 173

NullPointerException from array created in a method

I'm currently doing a simple university project about the arrays.

In my project I initialize and fill an array by using a method called "setArray", but when the program returns on the main method in which I try to print the array's content, it returns a NullPointerException.

public class Main {


public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int num[] = null;

    String command;

    setArray(in, num);



    for(int i = 0; i < num.length ; i++)
    {
        System.out.println(num[i]);
    }
}
private static void setArray(Scanner in, int[] num)
{
    System.out.println("Type the array size: ");
    int dim = in.nextInt();

    num = new int[dim];

    System.out.println("Size: " + num.length);

    System.out.println("Type the numbers' variability: ");

    int var = in.nextInt();

    int ran;

    for(int i = 0; i < num.length ; i++)
    {
        ran = (int) (Math.random() * var);

        num[i] = ran;
        System.out.println(num[i]);
    }
}

Upvotes: 0

Views: 77

Answers (2)

Deep
Deep

Reputation: 959

if you see your code you are declaring a local variable num in your setArray(scanner in,int[] num) method which is not visible in main function nor it is same as that you declared in main function . The variable array num in the main function is different from that in setArray() function.

Upvotes: 1

Tom Mac
Tom Mac

Reputation: 9853

Have a look at this question about whether Java is Pass By Reference

Your code would be better off like this:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int num[] = null;

    String command;

    num = setArray(in);

    for(int i = 0; i < num.length ; i++)
    {
        System.out.println(num[i]);
    }
}
private static int[] setArray(Scanner in)
{
    System.out.println("Type the array size: ");
    int dim = in.nextInt();

    int[] numToReturn = new int[dim];

    System.out.println("Size: " + numToReturn.length);

    System.out.println("Type the numbers' variability: ");

    int var = in.nextInt();

    int ran;

    for(int i = 0; i < numToReturn.length ; i++)
    {
        ran = (int) (Math.random() * var);

        numToReturn[i] = ran;
        System.out.println(numToReturn[i]);
    }
    return numToReturn;
}

Upvotes: 2

Related Questions