Objective: Create a simple stock market simulator in Java that allows users to buy and sell stocks, view their portfolio, and track the historical prices of a limited set of stocks. Starter code is given. Figure out what is missing and complete the project. Some of the requirements have been done.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class StockMarketSimulator {
static final int NUM_STOCKS = 6;
static String[] stockNames = new String[NUM_STOCKS];
static double[] stockPrices = new double[NUM_STOCKS];
static int[] userShares = new int[NUM_STOCKS];
static double userBalance = 10000.0;
public static void main(String[] args) {
initializeStockData();
Scanner scanner = new Scanner(System.in);
while (true) {
displayMenu();
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
displayStocks();
break;
case 2:
buyStock(scanner);
break;
case 3:
sellStock(scanner);
break;
case 4:
displayPortfolio();
break;
case 5:
savePortfolio();
System.out.println("Portfolio saved successfully.");
break;
case 6:
System.out.println("Exiting...");
System.exit(0);
break;
default:
System.out.println("Invalid choice. Please try again.");
}
updateStockPrices();
}
}
public static void initializeStockData() {
stockNames[0] = "Apple";
stockNames[1] = "Google";
stockNames[2] = "Amazon";
stockNames[3] = "Meta";
stockNames[4] = "Netflix";
stockNames[5] = "Tesla";
try (Scanner fileScanner = new Scanner(new
File("initial_stock_prices.txt"))) {
for (int i = 0; i < NUM_STOCKS; i++) {
stockPrices[i] = Double.parseDouble(fileScanner.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
public static void displayMenu() {
System.out.println("Stock Market Simulator");
System.out.println("1. View Stocks");
System.out.println("2. Buy Stocks");
System.out.println("3. Sell Stocks");
System.out.println("4. View Portfolio");
System.out.println("5. Save Portfolio");
System.out.println("6. Exit");
System.out.print("Select an option: ");
}
public static void displayStocks() {
System.out.println("Stocks:");
for (int i = 0; i < NUM_STOCKS; i++) {
System.out.println((i + 1) + ". " + stockNames[i] + " - $" +
stockPrices[i]);
}
}
public static void buyStock(Scanner scanner) {
displayStocks();
System.out.print("Select a stock to buy: ");
int stockIndex = scanner.nextInt() - 1;
scanner.nextLine(); // Consume newline
System.out.print("Enter the number of shares to buy: ");
int numShares = scanner.nextInt();
scanner.nextLine(); // Consume newline
//Your code goes here
}
public static void sellStock(Scanner scanner) {
displayPortfolio();
System.out.print("Select a stock to sell: ");
int stockIndex = scanner.nextInt() - 1;
scanner.nextLine(); // Consume newline
System.out.print("Enter the number of shares to sell: ");
int numShares = scanner.nextInt();
scanner.nextLine(); // Consume newline
//Your code goes here
}
public static void displayPortfolio() {
//Your code goes here
}
public static void savePortfolio() {
// Save portfolio to "portfolio.txt" file
//Your code goes here
}
public static void updateStockPrices() {
Random random = new Random();
for (int i = 0; i < NUM_STOCKS; i++) {
double variation = (random.nextDouble() - 0.5) * 10; // Simulate price
fluctuation
stockPrices[i] += variation;
if (stockPrices[i] < 1.0) {
stockPrices[i] = 1.0; // Minimum price
}
}
}
}

There are several missing parts in the code that need to be completed to fulfill the requirements of the stock market simulator:

1. In the "buyStock" method, after the user enters the number of shares to buy, you need to check if the user has enough balance to make the purchase. If they have sufficient balance, deduct the cost of the shares from their balance and update the number of shares owned for that stock. If they don't have enough balance, display a message informing them of the insufficient funds.

2. In the "sellStock" method, after the user selects a stock to sell and enters the number of shares to sell, you need to check if the user owns enough shares to make the sale. If they have enough shares, calculate the value of the sold shares based on the current stock price, add that value to the user's balance, and update the number of shares owned for that stock. If they don't have enough shares, display a message informing them of the insufficient shares.

3. In the "displayPortfolio" method, iterate over the userShares array and display the stock name, the number of shares owned, and the current value of those shares (based on the current stock prices) for each stock that the user owns.

4. In the "savePortfolio" method, open a FileWriter to the "portfolio.txt" file and write the stock names, number of shares owned, and current value of those shares (based on the current stock prices) for each stock that the user owns. Each line in the file should represent one stock owned by the user.

Below is the completed code with the missing parts added for the stock market simulator:

```
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class StockMarketSimulator {
static final int NUM_STOCKS = 6;
static String[] stockNames = new String[NUM_STOCKS];
static double[] stockPrices = new double[NUM_STOCKS];
static int[] userShares = new int[NUM_STOCKS];
static double userBalance = 10000.0;

public static void main(String[] args) {
initializeStockData();
Scanner scanner = new Scanner(System.in);
while (true) {
displayMenu();
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
displayStocks();
break;
case 2:
buyStock(scanner);
break;
case 3:
sellStock(scanner);
break;
case 4:
displayPortfolio();
break;
case 5:
savePortfolio();
System.out.println("Portfolio saved successfully.");
break;
case 6:
System.out.println("Exiting...");
System.exit(0);
break;
default:
System.out.println("Invalid choice. Please try again.");
}
updateStockPrices();
}
}

public static void initializeStockData() {
stockNames[0] = "Apple";
stockNames[1] = "Google";
stockNames[2] = "Amazon";
stockNames[3] = "Meta";
stockNames[4] = "Netflix";
stockNames[5] = "Tesla";
try (Scanner fileScanner = new Scanner(new File("initial_stock_prices.txt"))) {
for (int i = 0; i < NUM_STOCKS; i++) {
stockPrices[i] = Double.parseDouble(fileScanner.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}

public static void displayMenu() {
System.out.println("Stock Market Simulator");
System.out.println("1. View Stocks");
System.out.println("2. Buy Stocks");
System.out.println("3. Sell Stocks");
System.out.println("4. View Portfolio");
System.out.println("5. Save Portfolio");
System.out.println("6. Exit");
System.out.print("Select an option: ");
}

public static void displayStocks() {
System.out.println("Stocks:");
for (int i = 0; i < NUM_STOCKS; i++) {
System.out.println((i + 1) + ". " + stockNames[i] + " - $" + stockPrices[i]);
}
}

public static void buyStock(Scanner scanner) {
displayStocks();
System.out.print("Select a stock to buy: ");
int stockIndex = scanner.nextInt() - 1;
scanner.nextLine(); // Consume newline
System.out.print("Enter the number of shares to buy: ");
int numShares = scanner.nextInt();
scanner.nextLine(); // Consume newline

double totalPrice = stockPrices[stockIndex] * numShares;

if (totalPrice <= userBalance) {
userBalance -= totalPrice;
userShares[stockIndex] += numShares;
System.out.println("Stock bought successfully.");
} else {
System.out.println("Insufficient funds.");
}
}

public static void sellStock(Scanner scanner) {
displayPortfolio();
System.out.print("Select a stock to sell: ");
int stockIndex = scanner.nextInt() - 1;
scanner.nextLine(); // Consume newline
System.out.print("Enter the number of shares to sell: ");
int numShares = scanner.nextInt();
scanner.nextLine(); // Consume newline

if (numShares <= userShares[stockIndex]) {
double totalValue = stockPrices[stockIndex] * numShares;
userBalance += totalValue;
userShares[stockIndex] -= numShares;
System.out.println("Stock sold successfully.");
} else {
System.out.println("Insufficient shares.");
}
}

public static void displayPortfolio() {
System.out.println("Portfolio:");
for (int i = 0; i < NUM_STOCKS; i++) {
if (userShares[i] > 0) {
double currentValue = stockPrices[i] * userShares[i];
System.out.println(stockNames[i] + " - Shares: " + userShares[i] + ", Current Value: $" + currentValue);
}
}
}

public static void savePortfolio() {
try (FileWriter writer = new FileWriter("portfolio.txt")) {
for (int i = 0; i < NUM_STOCKS; i++) {
if (userShares[i] > 0) {
double currentValue = stockPrices[i] * userShares[i];
writer.write(stockNames[i] + "," + userShares[i] + "," + currentValue + "\n");
}
}
} catch (IOException e) {
System.out.println("Error writing to portfolio file: " + e.getMessage());
}
}

public static void updateStockPrices() {
Random random = new Random();
for (int i = 0; i < NUM_STOCKS; i++) {
double variation = (random.nextDouble() - 0.5) * 10; // Simulate price fluctuation
stockPrices[i] += variation;
if (stockPrices[i] < 1.0) {
stockPrices[i] = 1.0; // Minimum price
}
}
}
}
```

Note: Make sure to have a text file named "initial_stock_prices.txt" in the same directory as the Java file and populate it with initial stock prices for each stock, one price per line.