Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8616923
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T05:44:04+00:00 2026-06-12T05:44:04+00:00

I’m working on a stock exchange program as a project and so far I’ve

  • 0

I’m working on a stock exchange program as a project and so far I’ve gotten about 98% of it done, the only issue I am having is when I am trying to sell more shares than a current day holds. So for example, I buy 20 shares for $30 each on day 1 and 40 shares for $20 each on day 2. I then input saying I want to sell 30 shares for $20 each. What the code is supposed to do is sell all the shares from day one, and then sell 10 shares from day 2. However, what I’m getting is an EmptyQueueException being thrown. I feel that my sellShares method might be having the error when it goes into the final else statement with the while loop. However I cannot wrap my mind around what might be the error. I’ve been staring the code down for quite some time and I can’t seem to figure out a solution to this. Some assistance on this would greatly be appreciated. The following code is from my main class and the CircleArrayQueue class:

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 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T05:44:05+00:00Added an answer on June 12, 2026 at 5:44 am

    Your sellShares routine calls front() without checking to see if there is anything in the queue. If the queue is empty(), you get your exception.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I want use html5's new tag to play a wav file (currently only supported
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I'm trying to select an H1 element which is the second-child in its group

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.