如何在不删除 LinkedList 类和 TelevisionInventory 类之间的链接的情况下保留调试此代码

问题描述 投票:0回答:1

基本上,这是我的 TelevisionInventory 课程

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;

public class TelevisionInventory {
    private List<Television> tvList = new ArrayList<>();
    private LinkedList linkedList = new LinkedList();
    private Stack<Television> tvStack = new Stack<>();
    private Queue<Television> tvQueue = new LinkedList<>(); 
    private Scanner scanner = new Scanner(System.in);

    public void runInventorySystem() {
        int option;
        do {
            System.out.println("\nTelevision Inventory System");
            System.out.println("1. Add Television");
            System.out.println("2. Delete Television");
            System.out.println("3. Search and Display");
            System.out.println("4. Display All Televisions");
            System.out.println("5. Calculate");
            System.out.println("6. Move Data to LinkedList");
            System.out.println("7. Display data in LinkedList");
            System.out.println("8. Move data to Stack");
            System.out.println("9. Copy data to Stack");
            System.out.println("10. Display data in Stack");
            System.out.println("11. Move data to Queue");
            System.out.println("12. Copy data to Queue");
            System.out.println("13. Display data in Queue");
            System.out.println("14. Make an Expression Conversion");
            System.out.println("15. Exit");
            System.out.print("Select an option: ");
            option = scanner.nextInt();
            scanner.nextLine();
            System.out.println();

            switch (option) {
                case 1:
                    addTelevision();
                    break;
                case 2:
                    deleteTelevision();
                    break;
                case 3:
                    searchAndDisplay();
                    break;
                case 4:
                    displayInventory(tvList, "List of Televisions");
                    break;
                case 5:
                    calculateStats();
                    break;
                case 6:
                    moveDataToLinkedList();
                    break;
                case 7:
                    displayLinkedListData();
                    break;
                case 8:
                    moveDataToStack();
                    break;
                case 9:
                    copyDataToStack();
                    break;
                case 10:
                    displayStackData();
                    break;
                case 11:
                    moveDataToQueue();
                    break;
                case 12:
                    copyDataToQueue();
                    break;
                case 13:
                    displayQueueData();
                    break;
                case 14:
                    expressionConversion();
                    break;
                case 15:
                    System.out.println("Exiting...");
                    break;
                default:
                    System.out.println("Invalid option, please try again.");
                    break;
            }
        } while (option != 15);
        scanner.close();
    }

    private void addTelevision() {
        boolean continueAdding = true;
        while (continueAdding) {
            System.out.println();
            System.out.print("Enter TV ID: ");
            int id = scanner.nextInt();
            scanner.nextLine();
            System.out.print("Enter Brand: ");
            String brand = scanner.nextLine();
            System.out.print("Enter Size (in inches): ");
            int size = scanner.nextInt();
            System.out.print("Is it Digital? (true/false): ");
            boolean isDigital = scanner.nextBoolean();
            System.out.print("Enter Price: ");
            double price = scanner.nextDouble();
            scanner.nextLine();

            Television tv = new Television(id, brand, size, isDigital, price);
            tvList.add(tv);
            System.out.println("Television added successfully!");

            System.out.print("Do you want to add another TV? (true/false): ");
            continueAdding = scanner.nextBoolean();
            scanner.nextLine();
        }
    }

    private void deleteTelevision() {
        System.out.print("Enter TV ID to delete: ");
        int id = scanner.nextInt();
        boolean found = false;

        for (int i = 0; i < tvList.size(); i++) {
            if (tvList.get(i).getId() == id) {
                tvList.remove(i);
                found = true;
                System.out.println("Television with ID " + id + " has been removed.");
                break;
            }
        }

        if (!found) {
            System.out.println("No television with ID " + id + " found.");
        }
    }

    private void searchAndDisplay() {
        System.out.print("Enter TV ID or name to search: ");
        String input = scanner.nextLine();
        Television searchedTv = null;

        try {
            int id = Integer.parseInt(input);

            for (Television tv : tvList) {
                if (tv.getId() == id) {
                    searchedTv = tv;
                    break;
                }
            }
        } catch (NumberFormatException e) {

            for (Television tv : tvList) {
                if (tv.getBrand().equalsIgnoreCase(input)) {
                    searchedTv = tv;
                    break;
                }
            }
        }

        if (searchedTv != null) {
            System.out.println("Found Television: " + searchedTv);
        } else {
            System.out.println("Television not found.");
        }
    }

    private void displayInventory(List<Television> inventory, String type) {
        if (inventory.isEmpty()) {
            System.out.println(type + " is empty.");
        } else {
            System.out.println(type + " Inventory:");
            inventory.forEach(System.out::println);
        }
    }

    private void displayLinkedListData() {
        if (linkedList.isEmpty()) {
            System.out.println("LinkedList is empty.");
        } else {
            System.out.println("LinkedList Inventory:");
            System.out.println(linkedList.printList());
        }
    }

    private void calculateStats() {
        if (tvList.isEmpty()) {
            System.out.println("No Televisions in inventory.");
            return;
        }

        double sum = 0;
        double avg;
        double min = Double.MAX_VALUE;
        double max = Double.MIN_VALUE;

        for (Television tv : tvList) {
            double price = tv.getPrice();

            sum += price;

            if (price < min) {
                min = price;
            }

            if (price > max) {
                max = price;
            }
        }
        avg = sum / tvList.size();
        System.out.println("\nSum: RM " + sum + "\nAverage: RM " + avg + "\nMinimum: RM " + min + "\nMaximum: RM " + max);
    }

    private void moveDataToLinkedList() {
        for (Television tv : tvList) {
            linkedList.insertAtBack(tv);
        }
        tvList.clear();
        System.out.println("Data moved to LinkedList successfully.");
    }

    private void copyDataToStack() {
        for (int i = 0; i < linkedList.size(); i++) {
            try {
                tvStack.push((Television) linkedList.getNext());
            } catch (LinkedList.EmptyListException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
        System.out.println("Data copied to Stack successfully.");
    }

    private void moveDataToStack() {
        for (Television tv : tvList) {
            tvStack.push(tv);
        }
        tvList.clear();
        System.out.println("Data moved to Stack successfully.");
    }

    private void displayStackData() {
        if (tvStack.isEmpty()) {
            System.out.println("Stack is empty.");
        } else {
            System.out.println("Stack Inventory:");
            System.out.println(tvStack);
        }
        }

    private void moveDataToQueue() {
        for (Television tv : tvList) {
            tvQueue.offer(tv);
        }
        tvList.clear();
        System.out.println("Data moved to Queue successfully.");
    }

    private void copyDataToQueue() {
        for (Television tv : tvList) {
            tvQueue.offer(tv);
        }
        System.out.println("Data copied to Queue successfully.");
    }

    private void displayQueueData() {
        if (tvQueue.isEmpty()) {
            System.out.println("Queue is empty.");
        } else {
            System.out.println("Queue Inventory:");
            System.out.println(tvQueue);
        }
    }

    private void expressionConversion() {
        System.out.print("Enter infix expression to convert: ");
        String infix = scanner.nextLine();
        String postfix = PostFixConverter.convertToPostFix(infix);
        System.out.println("Postfix Expression: " + postfix);
    }
}
 

这是我的 LinkedList 类

public class LinkedList
{
     private Node head, tail, current;
    //Default LinkedList Class
     public LinkedList() { 
         head = tail = current = null; 
    }
 
     //To check whether is the linked list empty
     public boolean isEmpty() { 
         return head == null; 
    }
 
     // to print data
     public String printList()
     { 
         if (isEmpty())
             return "( empty list )";
         else
             return "(" + head + ")";
     }
 
     //To add new Object data at the front of the LinkedList
     public void insertAtFront(Object data)
     {
         if(isEmpty())
         head = tail = new Node(data);
         else
         head = new Node(data, head);
     }
     // Return the number of elements in the list
     public int size()
     {
         int count = 0;
         if (isEmpty())
             return count;
 
         current = head;
         while(current != null)
         {
             ++count;
             current = current.next;
         }
         return count;
     }
     //To add new Object data at the back of linked list
     public void insertAtBack(Object data)
     {
         if(isEmpty())
             head = tail = new Node(data);
         else
             tail = tail.next = new Node(data);
 
     }
 
     // Return the first element in the linked list 
     public Object getFirst() throws EmptyListException
     {
         if(isEmpty())
         throw new EmptyListException();
 
         current = head;
         return current.data;
     }
 
     // Return the next element in the linked list 
    public Object getNext() {
        if (current == null) {
            current = head;
        } else if (current != tail) {
            current = current.next;
        }
        return current != null ? current.data : null;
    }
 
     // Return the last element in the linked list 
     public Object getLast() throws EmptyListException
     {
         if(isEmpty())
             throw new EmptyListException();
 
         return tail.data;
     }
     
     // Remove the first element in the linked list
     public Object removeFromFront() throws EmptyListException
     {
         if(isEmpty())
             throw new EmptyListException();
 
             Object d = head.data;
 
         if(head==tail)
             head=tail=null;
         else
        {
             Node curr = head;
             head = head.next;
             curr.next = null;
         }
 
         return d;
 
     }
 
    // Remove the last element in the linked list
     public Object removeFromBack() throws EmptyListException
     {
         if(isEmpty())
             throw new EmptyListException();
 
         Object d = tail.data;
 
         if(head==tail)

         head=tail=null;
         else
        {
         Node curr = head;
         while(curr.next != tail)
         curr = curr.next;
 
         tail = curr;
         curr.next = null;
         }
 
         return d;
     }
     
    public class EmptyListException extends RuntimeException{
        public EmptyListException(){
            super("The list is empty");
        }
    }
}

问题出现在第11行,仅在'<>'部分有错误。我使用的编译器说 “无法推断 LinkedList 的参数类型。原因:不能将 '<>' 与非泛型类 LinkedList 一起使用。”

我认为我需要告诉的另一个线索是 LinkedList 类具有到节点的链接,并且 LinkedList 类是 Queue 类和 Stack 类的父类。 类之间关系图

那么,问题是,有没有办法在不删除 TelevisionInventory 类和 LinkedList 类之间的链接的情况下调试此代码?

我尝试将 import.java.util.LinkedList 添加到 TelevisionInventory 类中。但是,它们之间的联系消失了。

我还尝试删除 LinkedList 类并将所有代码放入 TelevisionInventory 类中。但是,程序变得太混乱了,我不知道将堆栈类和队列类放在哪里。

java algorithm linked-list queue stack
1个回答
0
投票

您的

LinkedList
必须实现
Queue<Television>
,因为您尝试将其分配给此类型的变量。

你可以这样做(通过使用泛型):

public class LinkedList<T> implements Queue<T> {
...
}

您需要实现为

Queue
定义的方法 并且您还应该更改我们自己的方法的类型以使用泛型类型
T

 public void insertAtBack(T data)
 public T getFirst() throws EmptyListException
 public T getNext() {
 public T getLast() throws EmptyListException
 public T removeFromFront() throws EmptyListException
 public T removeFromBack() throws EmptyListException

备注:
由于您将 LinkedList 实例分配给 Queue 类型的变量,您将只能访问 Queue 中定义的方法(对于其他方法,您需要首先将类型转换为 LinkedList)。

© www.soinside.com 2019 - 2024. All rights reserved.