有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组Java:EmptyQueueException在处理方法之前引发

我正在做一个股票交易项目,到目前为止,我已经完成了大约98%的工作,唯一的问题是当我试图卖出比当前持有的股票更多的股票时。例如,我在第一天以每股30美元的价格购买了20股股票,在第二天以每股20美元的价格购买了40股股票。然后我输入说我想以每股20美元的价格卖出30股。代码应该做的是从第一天开始卖出所有股票,然后从第二天开始卖出10股。然而,我得到的是一个EmptyQueueException被抛出。我觉得我的sellShares方法在使用while循环进入最终的else语句时可能会出错。然而,我无法集中精力思考可能出现的错误。我已经盯着代码看了很长一段时间了,我似乎找不出解决这个问题的办法。在此方面提供一些帮助将不胜感激。以下代码来自我的主类和CircleArrayQueue类:

import java.util.Scanner;
import java.lang.Integer;

public class StockTran {
String command = "";
int gain = 0;
int totalPrice = 0;         // totalPrice variable will keep of gain or loss of shares being sold
int shareTracker = 0;       // shareTracker variable will keep track of shares being bought and sold
String[] stockParts = null;
CircleArrayQueue Q;
boolean quit = false;

public StockTran(String inputCommand) {
    try {
        Q = new CircleArrayQueue(32);
        Scanner conReader = new Scanner(System.in);
        this.command = inputCommand.toLowerCase();
        this.stockParts = command.split("\\s"); // splits the input into three parts

        while (quit == false) {     // will loop until user says "q" to quit program
            if (this.stockParts[0].equals("q")) {       // ends transaction and terminates program
                System.out.println("Share trading successfully terminated.");
                quit = true;
                System.exit(0);     // exits the program
            }

            if (this.stockParts == null || this.stockParts.length > 3) {
                System.out.println("That is an invalid input. Please try again.");
            }

            if (stockParts[0].equals("b")) {        // checks to see if it is a buying of shares
                int shares = Integer.parseInt(stockParts[1]);       // stores share amount
                int value = Integer.parseInt(stockParts[2]);        // stores selling value
                buyShares(shares, value);       // calls buyShares method and adds share to queue
            }
            else if (stockParts[0].equals("s")) {       // checks to see if it is a selling of shares
                int shares = Integer.parseInt(stockParts[1]);
                int value = Integer.parseInt(stockParts[2]);
                sellShares(shares, value);      // calls sellShares method
            }
            else if (stockParts[0].equals("c")) {       // checks to see if it is capital gain
                gain = capitalGain();       // calls capitalGain and calculates net gain
                System.out.println("Capital gain is " + gain);
            }
            else {
                System.out.println("That is an invalid input. Please try again.");      // any other input is invalid
            }

            System.out.println("Enter your next command, or press 'q' to quit: ");
            command = conReader.nextLine().toLowerCase();
            stockParts = command.split("\\s");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}


public void buyShares(int shareAmount, int sharePrice) {        // takes in share total and values for each share
    shareTracker = shareTracker + shareAmount;  // adds to amount of shares bought
    Node temp = new Node(shareAmount, sharePrice);      // stores values into node
    try {
        Q.enqueue(temp);        // enqueues the node into the CircularQueue
    } catch (FullQueueException e) {
        e.printStackTrace();
    }
}

public void sellShares(int shareAmount, int sharePrice) throws Exception {
    Node temp = new Node();     // stores values into node
    int tempShare = 0;
    try {
            temp = Q.front();       // gets the first node from CircleArrayQueue and stores it in temporary node
            int share = temp.getShare();
            int price = temp.getPrice();
            System.out.println(Q.size());

            if (shareAmount > shareTracker) {       // throws exception if trying to sell more shares than purchased
                throw new Exception ("You don't have that many shares to sell.");
            }
            else if (share > shareAmount) {     // checks to see if first node has a larger share amount or less
                temp.setShare(share - shareAmount);     // will decrease amount sold from the first days share
                shareTracker = shareTracker - shareAmount;
                totalPrice = shareAmount * (sharePrice - price) + totalPrice;       // calculates total profit or loss
            }
            else if (share == shareAmount) {
                Q.dequeue();
                shareTracker = shareTracker - shareAmount;          // updates shareTracker to show how many shares are remaining
                totalPrice = shareAmount * (sharePrice - price) + totalPrice;
            }
            else {
                while (shareAmount != tempShare) {      // will loop until it sells total share amount user wanted
                    Node temp2 = Q.dequeue();           // removes another node from CircleArrayQueue
                    int newShare = temp2.getShare();
                    int newPrice = temp2.getPrice();
                    tempShare = tempShare + newShare;   // adds the shares together to check if while loop condition still holds
                    totalPrice = shareAmount * (sharePrice - newPrice) + totalPrice;
                    sellShares(shareAmount - tempShare, sharePrice);        // recursively calls sellShares on new amount of shares
                }
            }
    } catch (EmptyQueueException e) {
        e.printStackTrace();
    }
}


public int capitalGain() {      // returns the total net gain or loss in share trading
    return totalPrice;
}


public static void main(String[] args) {
    String inputCommand = "";
    Scanner mainReader = new Scanner(System.in);

    System.out.println("Enter 'b' to purchase share, 's' to sell share, 'c' for capital gain, or 'q' to quit: ");
    inputCommand = mainReader.nextLine();

    StockTran tran = new StockTran(inputCommand);
}
}




public class CircleArrayQueue implements Queue {
    protected Node Q[];     // initializes an empty array for any element type
    private int MAX_CAP = 0;        // initializes the value for the maximum   array capacity
private int f, r;

public CircleArrayQueue(int maxCap) {
    MAX_CAP = maxCap;
    Q = new Node[MAX_CAP];  // sets Q to be a specific maximum size specified
    f = 0;      // sets front value to be 0
    r = 0;      // sets rear value to be 0;
}

public int size() {
    return (MAX_CAP - f + r) % MAX_CAP;     // returns the size of the CircularArrayQueue
}

public boolean isEmpty() {      // if front and rear are of equal value, Queue is empty
    return f == r;
}

public Node front() throws EmptyQueueException {        // method to get the front value of the CircularArrayQueue
    if (isEmpty()) throw new EmptyQueueException("Queue is empty.");
        return Q[f];        // returns object at front of CircularArrayQueue
}

public Node dequeue() throws EmptyQueueException {  // method to remove from the front of the CircularArrayQueue
    if (isEmpty()) throw new EmptyQueueException("Queue is empty.");
        Node temp = Q[f];       // stores front object in local variable
        Q[f] = null;        // sets the value to be null in the array
        f = (f + 1) % MAX_CAP;      // sets the new front value to be this
        return temp;        // returns the object that was originally in the front
}

public void enqueue(Node element) throws FullQueueException {       // method to add to the end of the CircualarArrayQueue
    if (size() == MAX_CAP - 1) throw new FullQueueException("Queue has reached maximum capacity.");
        Q[r] = element;     // stores the new element at the rear of array
        r = (r + 1) % MAX_CAP;      // sets the new rear value to be the location after element insertion
}
}

共 (1) 个答案

  1. # 1 楼答案

    您的sellShares例程调用front(),而不检查队列中是否有任何内容。如果队列为空()