0

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]);
    }
}
2
  • Could you provide the error log? What line is the NPE happening on? Commented Jan 28, 2015 at 15:25
  • 3
    stackoverflow.com/questions/40480/… Commented Jan 28, 2015 at 15:26

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

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.