简体   繁体   中英

java.lang.NullPointerException when accessing inner class field

I am getting a null pointer exception from the code below at line 19, seq[index].value = lo; . The sequence class has a value field with integer type, but I think the problem is to access the array of seq instance.

public class ImprovedFibonacci {

class Sequence{
    int value = 0;
    boolean isEven = false;
}

public static void main(String[] args){

    final int MAX_LOOP = 20;
    int lo = 1;
    int hi = 1;
    int i = 0;
    String mark = "-";

    int index = 0;
    ImprovedFibonacci.Sequence[] seq = new ImprovedFibonacci.Sequence[MAX_LOOP];
    seq[index].value = lo;

    System.out.println("Fibonacci seq 1 : " + lo);
    System.out.println("Sequence class index: "+index+"value: "+seq[index].value);

    for(i=MAX_LOOP;i>=1;i--) {
        hi = hi + lo;
        lo = hi - lo;
        index++;
        if(hi % 2 == 0){
            mark = "-";
            seq[index].isEven = true;
        }else{
            mark = "";
        }

        System.out.println(i + " : " + hi + mark);
        seq[index].value = hi;
        System.out.println("Sequence class index: "+index+"value: "+seq[index].value+"IsEven: "+seq[index].isEven);
    }
}
}

You create array, but never fill with objects.

ImprovedFibonacci.Sequence[] seq = new ImprovedFibonacci.Sequence[MAX_LOOP];
    seq[index].value = lo;

So seq[index] returns null, and null.value gives you a NullPointerException

For instance:

Object[] array = new Object[10];

it's create array with 10 elements but every element will be null.

Here is sample code: http://ideone.com/0gIYm

seq is an array with MAX_LOOP space, but nothing has been instantiated in it. The first element ( seq[0] ) is null, as are all other elements.

seq[index] = new ImprovedFibonacci.Sequence();
seq[index].value = lo;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM