0

私はプロジェクトとして証券取引所プログラムに取り組んでおり、これまでのところその約98%を完了しています。私が抱えている唯一の問題は、現在よりも多くの株を売ろうとしているときです。たとえば、1日目に20株を30ドルで購入し、2日目に40株を20ドルで購入します。次に、30株を20ドルで販売したいと入力します。コードが行うことになっているのは、初日からすべての株を売り、次に2日目から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
}
}
4

1 に答える 1

0

SellSharesルーチンは、キューに何かがあるかどうかを確認せずにfront()を呼び出します。キューがempty()の場合、例外が発生します。

于 2012-09-26T07:12:22.560 に答える