开发者

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.pr开发者_StackOverflow中文版intln("Enter numbers to check");
        arr2[i] = scan.nextInt();
    }

    if(arr1 == arr2)
        return true;

    return false;
}


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.


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;


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....:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜