Untitled

 avatar
unknown
java
6 months ago
9.2 kB
5
Indexable
import java.util.*;
import java.io.*;

// Nimai Belur
// 10/9/2024
// CSE 122
// TA: Cora Supasatit
// This class is a stock simulator. It allows you to buy and sell stocks for your portfolio, and you can save everything to a file that contains your
// portfolio at the end
public class Stonks {
    public static final String STOCKS_FILE_NAME = "stonks.tsv";

    public static void main(String[] args) throws FileNotFoundException {
        // TODO: write main method here
        //Create Scanner for stonks file and populating empty arrays with stock info, then creating second Scanner for user input
        File stocks = new File(STOCKS_FILE_NAME);
        Scanner fileScan = new Scanner(stocks);
        int numStocks = Integer.parseInt(fileScan.nextLine());
        String[] stockNames = new String[numStocks];
        double[] prices = new double[numStocks];
        double[] portfolio = new double[numStocks];
        populateArrays(stockNames, prices, numStocks, fileScan);
        Scanner input = new Scanner(System.in);
        String response = input.nextLine();

        //Main loop checking if you want to quit
        while(!response.equalsIgnoreCase("Q")){
            //buy stock
            if(response.equalsIgnoreCase("B")){
                buyStock(stockNames, prices, portfolio, input);
            //sell stock
            } else if(response.equalsIgnoreCase("Se")){
                sellStock(stockNames, portfolio, input);
            //save portfolio
            } else if(response.equalsIgnoreCase("S")){
                savePortfolio(portfolio, stockNames, input);
            //user entered invalid character
            } else {
                System.out.println("Invalid choice: " + response);
                System.out.println("Please try again");
            }
            //reprompting
            response=reprompt(input);
        }
        //print value of portfolio at the end
        printValue(portfolio, prices);
    }

    // Behavior: Asks the user for a stock and budget, and adds the correct amount of shares to the user's porfolio depending on the budget.
    // Asks user to retry if their budget is too low.
    // Exceptions: None
    // Returns: Nothing
    // Parameters: 
    //    - stockNames: String[] - array containing the names of available stocks
    //    - prices: double[] - array containing the prices of each stock
    //    - portfolio: double[] - array representing the number of shares the user owns for each stock
    //    - input: Scanner - Scanner object to get user input
    public static void buyStock(String[] stockNames, double[] prices, double[] portfolio, Scanner input){
        System.out.print("Enter the stock ticker: ");
        String name = input.nextLine();
        //gets the index of the stock in stockNames
        int stockIndex = nameAsIndex(name, stockNames);
        System.out.print("Enter your budget: ");
        String budgetString = input.nextLine();
        //gets budget as a double
        double budget = Double.parseDouble(budgetString);
        //if budget less than $5, user cannot buy stock, otherwise add however many shares they can buy to their portfolio
        if(budget<5){
            System.out.println("Budget must be at least $5");
        } else {
            portfolio[stockIndex] += budget/prices[stockIndex];
            System.out.println("You successfully bought " + name + ".");
        }
        
    }

    // Behavior: Asks the user what stock they want to sell and how much. Sells that many shares if the user has that many, otherwise user must try again
    // Exceptions: N/A
    // Returns: Nothing
    // Parameters: 
    //    - stockNames: String[] - array containing the names of available stocks
    //    - portfolio: double[] - array representing the number of shares the user owns for each stock
    //    - input: Scanner - Scanner object to get user input
    public static void sellStock(String[] stockNames, double[] portfolio, Scanner input){
        System.out.print("Enter the stock ticker: ");
        String name = input.nextLine();
        int stockIndex = nameAsIndex(name, stockNames);
        //amount of shares to sell as a double
        System.out.print("Enter the number of shares to sell: ");
        String numShares = input.nextLine();
        double shares = Double.parseDouble(numShares);
        //prevents users from selling more shares than they have
        if(shares>portfolio[stockIndex]){
            System.out.println("You do not have enough shares of " + name + " to sell " + shares 
            + " shares.");
        } else {
            portfolio[stockIndex]-=shares;
            System.out.println("You successfully sold " + shares + " shares of " + name + ".");
        }
    }

    // Behavior: Saves the user's current portfolio to a file by looking through their portfolio and printing stocks that 
    // the user has more than 0 shares of to the new file
    // Exceptions: Throws FileNotFoundException
    // Returns: Nothing
    // Parameters: 
    //    - portfolio: double[] - array representing the number of shares the user owns for each stock
    //    - stockNames: String[] - array containing the names of available stocks
    //    - input: Scanner - Scanner object to get user input
    public static void savePortfolio(double[] portfolio, String[] stockNames, Scanner input) throws FileNotFoundException {
        System.out.print("Enter new portfolio file name: ");
        String fileName = input.nextLine();
        File portfolioFile = new File(fileName);
        PrintStream fileWrite = new PrintStream(portfolioFile);
        for(int i=0; i<portfolio.length; i++){
            //Only puts stock info in portfolio if you have more than 0 shares of it
            if(portfolio[i]>0.0){
                fileWrite.println(stockNames[i]+" "+portfolio[i]);
            }
            
        }
    }

    // Behavior: Maps the stock ticker name to its index in the stockNames array. 
    //    Returns -1 if the stock ticker is not found.
    // Exceptions: N/A
    // Returns: int - index of the stock in the stockNames array, or -1 if not found
    // Parameters: 
    //    - name: String - stock ticker to look for
    //    - stockNames: String[] - array containing the names of available stocks
    public static int nameAsIndex(String name, String[] stockNames){
        for(int i=0; i<stockNames.length; i++){
            if(name.equals(stockNames[i])){
                return i;
            }
        }
        return -1;
    }

    // Behavior: Calculates and prints the total value of the user's portfolio by multiplying each amount of 
    // shares in the portfolio by the share price for the corresponding company
    // Exceptions: N/A
    // Returns: Nothing
    // Parameters: 
    //    - portfolio: double[] - array representing the number of shares the user owns for each stock
    //    - prices: double[] - array containing the prices of each stock
    public static void printValue(double[] portfolio, double[] prices){
        double total=0.0;
        for(int i=0; i<portfolio.length; i++){
            total+=portfolio[i]*prices[i];
        }
        System.out.println("Your portfolio is currently valued at: $" + total);
    }

    // Behavior: Reads the stock names and prices from the file and populates the stockNames and prices arrays.
    //    It also prints out the available stocks and their prices to the user.
    // Exceptions: N/A
    // Returns: Nothing
    // Parameters: 
    //    - stockNames: String[] - array to populate with the names of stocks
    //    - prices: double[] - array to populate with the prices of stocks
    //    - numStocks: int - number of stocks to populate
    //    - fileScan: Scanner - Scanner object to read the file
    public static void populateArrays(String[] stockNames, double[] prices, int numStocks, Scanner fileScan) {
        System.out.println("Welcome to the CSE 122 Stocks Simulator!");
        System.out.println("There are " + numStocks + " stocks on the market:");
        //Skips over the line that contains the name of each category in stonks file
        fileScan.nextLine();
        for(int i=0; i<numStocks; i++){
            stockNames[i]=fileScan.next();
            prices[i]=Double.parseDouble(fileScan.next());
            System.out.println(stockNames[i]+": "+prices[i]);
            if(fileScan.hasNextLine()){
                //Skips over dividend yield and P/E ratio
                fileScan.nextLine();
            }
        }
        System.out.println();
        //User prompt
        System.out.println("Menu: (B)uy, (Se)ll, (S)ave, (Q)uit");
        System.out.print("Enter your choice: ");
    }

    // Behavior: Prompts the user to choose an action (Buy, Sell, Save, or Quit) and returns their input.
    // Exceptions: N/A
    // Returns: String - the user's input command
    // Parameters: 
    //    - input: Scanner - Scanner object to get user input
    public static String reprompt(Scanner input){
        System.out.println();
        System.out.println("Menu: (B)uy, (Se)ll, (S)ave, (Q)uit");
        System.out.print("Enter your choice: ");
        String in = input.nextLine();
        return in;
    }
}
Editor is loading...
Leave a Comment