在范围之间添加数字

时间:2015-12-18 23:33:59

标签: java nullpointerexception linked-list

我制作了一个程序,它接受用户输入的起始编号,结束编号和增量。这将添加到Range(链接列表)。我想添加一个用户输入到此Range的号码,并将输入的号码放在每个号码之间。

主要

public class PDEMain {

public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a start number: ");
        Integer startNum = input.nextInt();

        System.out.print("Enter end number: ");
        Integer endNum = input.nextInt();

        System.out.print("Enter increment: ");
        Integer increment = input.nextInt();

        Range obj = new Range(startNum, endNum, increment);
        obj.display();

        System.out.print(" Enter 1 for take:\n "
                        + "Enter 2 for drop:\n "
                        + "Enter 3 for repeat:\n "
                        + "Enter 4 for interpose: ");
        Integer number = input.nextInt();

        if(number == 1) {
            obj.take();
        }

        if(number == 2) {
            obj.drop();
        }

        if(number == 3) {
            obj.repeat();
        }

        if(number == 4) {
            obj.interpose();
        }        
    }
}

范围:

public class Range implements Cloneable {

private Integer data; // holds the data
private Range link; //holds the link
private Range head; //refers to head of linked list
private Integer startValue;
private Integer endValue;
private Scanner input;

public Range(Integer data, Range link) {

    this.data = data;
    this.link = link;
}

public Range(Integer data, Range link, Range head) {
    this.data = data;
    this.link = link;
    this.head = head;
}


public Range(Integer start, Integer end,Integer increment) {
     if(start == null) {
        startValue = 0;
    }

     if(increment == null) {
        if(start < end) {
            increment++;
        } else {
            increment--;
        }
    }

    for (int i = start; i <= end; i+= increment) {
        addNodeAfter(i);  
    }
}

public Integer getData() {
    return data;
}

public void setData(Integer data) {
    this.data = data;
}

public Range getLink() {
    return link;
}

public void setLink(Range link) {
    this.link = link;
}

public Range getHead() {
    return head;
}

public void setHead(Range head) {
    this.head = head;
}

我有以下interpose方法的代码:

public void interpose() {
    System.out.println("What number would you like to interpose? ");
    Integer answer = input.nextInt();

    Range cursor = head;

    for (int i = 0; i <= answer; i++) {
        System.out.print(cursor.getData() + " ");
        this.link = new Range(answer, this.link);
        cursor = cursor.getLink();     
    }
    System.out.print("New Range: ");
    display();
    modify();
    anotherRange();
}

我在Integer answer = input.nextInt();

得到一个NullPointerException

有关我为什么会遇到此异常以及我的逻辑是否正确的任何提示?

1 个答案:

答案 0 :(得分:3)

尝试将Scanner类添加到interpose()方法中,如下所示:

 Scanner input = new Scanner(System.in);
 Integer answer = input.nextInt();