【发布时间】:2015-10-24 17:55:57
【问题描述】:
如果您能帮我解决下一个问题,我将不胜感激。所以我制作了 Item 类的对象并将其放入链表中。当我尝试从函数“itemCost”打印列表时,该函数一直在无限循环中打印第一个对象的内容。
主要 -
import java.util.*;
public class Main {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
String name;
double price;
int id, amount;
Item s;
Node<Item> a = null, p = null, tmp = null;
System.out.println("Enter number of items: ");
int n = reader.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("Enter id: ");
id = reader.nextInt();
System.out.println("Enter name: ");
name = reader.next();
System.out.println("Enter price: ");
price = reader.nextDouble();
System.out.println("Enter amount: ");
amount = reader.nextInt();
s = new Item(id, name, amount, price);
tmp = new Node<Item>(s);
if (a == null) {
a = tmp;
p = tmp;
} else {
a.setNext(tmp);
p = tmp;
}
}
itemCost(a);
}
// This is the problem. It's print in infinite loop the first Item only
// instead all of the items in the list
public static void itemCost(Node<Item> s) {
Node<Item> p = s;
while (p != null) {
System.out.println(p.toString());
System.out.println("Total: " + p.getValue().getTotal());
s.getNext();
}
}
}
- 我不知道是添加Node还是Item的类所以如果您需要它们也请写信给我,我会添加。谢谢
【问题讨论】:
标签: java class linked-list nodes