Why does Java throw NullPointerException here?

后端 未结 5 1993
半阙折子戏
半阙折子戏 2020-11-30 15:09
public class Test {

    public int [] x;

    public Test(int N)
    {
       int[] x = new int [N];
       for (int i=0;i

        
相关标签:
5条回答
  • 2020-11-30 15:17

    Everyone has given the code that would work. But the reason is something called as variable scoping. When you create a variable (by saying int[] x, you are declaring x as an integer array and by saying x = new int[4] you are assigning a new array to x). If you use the same variable name x everywhere and keep assigning things to it, it'll be the same across your class.

    But, if you declare int[] x one more time - then you are creating one more variable with the name x - now this can result in duplicate variable error or if you're declaring in a narrower 'scope', you will be overriding your previous declaration of x.

    Please read about java variable scopes to understand how scoping works.

    0 讨论(0)
  • 2020-11-30 15:22

    what you did is called shadowing you shadowed your field x with local variable x. so all you need to do is avoiding this:

    int[] x = new int [N]; is wrong, if you want your field to initialize instead of a local variable then you could do something like : x = new int [N]; for more information read this

    0 讨论(0)
  • 2020-11-30 15:25

    change the first line in constructor from

    int[] x = new int [N];
    

    to

    x = new int [N];
    

    it should work...

    Actually in constructor when you say int[] x, it is creating one more local variable instead setting data to public variable x... if you remove int[] from first line of constructor then it initizes the public variable & you will be able to print them in main() method

    0 讨论(0)
  • 2020-11-30 15:27
     int size=reader.readInt();  // size < 3
     StdOut.println(N.x[3]); // length of x[] less than 3, so x[3] case NullPointException
    
    0 讨论(0)
  • 2020-11-30 15:28

    Inside public Test(int n):

    Change

    int[] x = new int [N]; // Creating a local int array x
    

    to

    x = new int [N]; // Assigning it to x
    
    0 讨论(0)
提交回复
热议问题