如果您帮助我解决下一个问题,我将不胜感激。所以我创建了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();
}
}
}
答案 0 :(得分:0)
你的while循环永远不会改变它在条件中检查的变量,所以它永远不会终止。
尝试:
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());
p = p.getNext();
}
}