gpt4 book ai didi

java - 在范围之间添加一个数字

转载 作者:行者123 更新时间:2023-11-29 04:54:08 24 4
gpt4 key购买 nike

我制作了一个程序,它接受用户输入的开始编号、结束编号和增量。这被添加到 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

关于为什么我得到这个异常以及我的逻辑是否正确的任何提示?

最佳答案

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

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

关于java - 在范围之间添加一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34365513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com