在子类

时间:2016-04-13 19:23:29

标签: java arraylist nullpointerexception subclass

在访问子类中的ArrayList时,我得到NullPointerException。奇怪的是我可以通过getter访问主类中的ArrayList,我也可以访问创建ArrayList的类中的ArrayList。

这是主要的类(这里应该调用Everything):

package fsalab4;

public class FSAlab4 {
    public static void main(String[] args) {
        FinateStateMachine FSM = new FinateStateMachine();

        FSM.getStringFromUser();
        FSM.readString();

        state1 state1 = new state1();

        state1.classSwitch();
    }
}

这是创建ArrayList的类:

package fsalab4;

import java.util.ArrayList;
import java.util.Scanner;


public class FinateStateMachine {
    private int hops;
    private String userString;
    ArrayList<Character> charList;

    public void getStringFromUser(){
        Scanner scanner = new Scanner(System.in);

        userString = scanner.next();
    }

这是创建ArrayList的方法。

    public void readString(){
        charList = new ArrayList<>();
        for(int i = 0; i < getUserString().length(); i++){  
            if(getUserString().charAt(i) == 'a'|| getUserString().charAt(i) == 'b'){
                charList.add(getUserString().charAt(i));
            }
        }
    }

    public void madeHop(){
        hops++;
    }

    public int getHops() {
        return hops;
    }

    public String getUserString() {
        return userString;
    }

这是ArrayList的getter:

    public ArrayList<Character> getCharList() {
        return charList;
    }
}

这是访问ArrayList的类之一。这也是发生错误的类:

package fsalab4;

public class state1 extends FinateStateMachine{
    public void classSwitch(){
        if(super.getCharList().get(super.getHops()) == 'a'){
            state6 state6 = new state6();

            state6.classSwitch();
            System.out.println("in state 1 switch state 6");
        }else{
            state2 state2 = new state2();

            state2.classSwitch();
            System.out.println("in state 1 switch state 2");
        } 
        super.madeHop();
    }
}

0 个答案:

没有答案