简体   繁体   English

打印链表陷入无限循环[关闭]

[英]Print linked list stuck in infinite loop [close]

I'll appreciate if you help me fix the next problem. 如果您能帮助我解决下一个问题,我们将不胜感激。 So I made object of Item class and put it in a linked list. 因此,我将Item类作为对象并将其放在链接列表中。 When I try to print the list from the function "itemCost" that prints the contents of the first object all the time in infinite loop. 当我尝试从函数“ itemCost”中打印列表时,该函数始终无限循环地打印第一个对象的内容。

Main - 主-

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();
        }
    }
}
  • I didn't know whether to add the class of Node or Item So please if you need them also wrote to me and I will add. 我不知道是否要添加Node或Item的类,所以如果您需要它们,也请写信给我,我会添加。 Thanks 谢谢

Your while loop never changes the variable it checks in its condition, so it never terminates. while循环永远不会更改其检查条件的变量,因此它永远不会终止。

Try : 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM