【问题标题】:Print linked list stuck in infinite loop [close]打印卡在无限循环中的链表 [关闭]
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 非常感谢!! .我应该注意到了。
    猜你喜欢
    • 1970-01-01
    • 2013-10-07
    • 2013-05-04
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多