java - 打印陷入无限循环的链表

标签 java class linked-list nodes

如果您帮我解决下一个问题,我将不胜感激。所以我创建了 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 类,所以如果您需要它们也请写信给我,我会添加。谢谢

最佳答案

您的 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();
  }
}

关于java - 打印陷入无限循环的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33321467/

相关文章:

java - 在 Class.forName(...) 加载的 jar 上使用 getResourceAsStream

c++ - 如何将链表的节点直接链接到节点指针?

java - 将元素添加到双链表

java - 解决源代码依赖关系

PHP 仅包含外部类一次

java - Glassfish 4无法用jdk1.7.0_51启动

c++ - 如何跟踪通话统计? C++

performance - `any`/`all` 的 Haskell/GHC 性能

JavaFX:使用箭头键和空格键移动图像

java - SLF4J:无法加载类“org.slf4j.impl.StaticLoggerBinder post log4j Remediation