Splitter
Splitter

Reputation: 35

Comparing 2 int arrays

Can anyone tell me whats wrong in this method and why it gives a nullpointerException ?

public boolean check(){

    Scanner scan = new Scanner(System.in);

    int[] arr1 = new int []{1,2,3};
    int[] arr2 = new int[]{};

    for(int i = 0;i<arr1.length;i++)
    {
        System.out.println("Enter numbers to check");
        arr2[i] = scan.nextInt();
    }

    if(arr1 == arr2)
        return true;

    return false;
}

Upvotes: 2

Views: 1780

Answers (3)

Abhimanyu Srivastava
Abhimanyu Srivastava

Reputation: 506

you are not allocation any size for arr2 so it results in declaring its size to 0 in which you input values finally resulting in null values.... and also you cannot compare array like you have done and even if you can one array being null wont give any result........... try initializng arr2 with a size and den instead of doing (arr1==arr2)...try looping and finding the answer...will get you the answer....... hope if helps....:)

Upvotes: 2

ryanprayogo
ryanprayogo

Reputation: 11817

You are not allocating enough memory for arr2. In this case, arr2 is initialized with the length of 0.

Your 3rd line should be something like:

int[] arr2 = new int[arr1.length];

In addition, if(arr1 == arr2) is not the correct way to compare whether two arrays have the same elements.

Instead, you can use java.util.Arrays.equals() to check whether your two arrays are equal.

Upvotes: 5

patapizza
patapizza

Reputation: 2398

Scanner scan = new Scanner(System.in);
int[] arr1 = new int[]{1,2,3};
int[] arr2 = new int[arr1.length];
for (int i = 0 ; i < arr1.length ; i++) {
  System.out.println("Enter numbers to check");
  arr2[i] = scan.nextInt();
  if (arr1[i] != arr2[i])
    return false;
}
return true;

Upvotes: 2

Related Questions