In: Computer Science
You are required to read in a list of stocks from a text file “stocks.txt” and write the sum and average of the stocks’ prices, the name of the stock that has the highest price, and the name of the stock that has the lowest price to an output file. The minimal number of stocks is 30 and maximal number of stocks in the input file is 50. You can download a input file “stocks.txt” from Canvas. When the program runs, it should do the following:
May or may not use the Stock Class created in Assignment 6 and modify it as it is needed.
The Stock class must have a constructor with 3 parameters that correspond to the 3 fields: Stock Name, Symbol, Price. o For the argument constructor, set the value of 3 fields based on the arguments.
The Stock class must have accessors and mutators for all of its private fields.
The setter methods must protect a user from setting the price into negative number. You can set the values to 0 if a user tries to change them to negative values.
The program will ask user to enter a name of the input file. If the input file does not exist, the program should print an error message and terminate immediately. o To check if a file opens successfully, please use the following example as a reference: File myFile = new File(“stocks.txt”); if (!myFile.exists()){ System.exit(0); }
If the file opens successfully, then the program reads stocks’ information and store it into an array of stocks. Each element of the array MUST be a Stock object. You should use ArrayList class.
The program calculate the sum and average of the stocks’ prices.
The program finds the name of the stock with the highest price and the name of the stock with the lowest price.
The program asks user to enter a name for an output file. Then it creates the output file and write the sum, average, names of the stocks with highest and lowest price to the file.
Note: your program must be user-friendly and intuitive. This is a part of your grade. In other words, even if your program does everything the problem statement states, your grade may be reduced because of difficulty to it. Input This program requires that you read in the following data values:
An input file name.
An output file name.
An input file that contains a list of stocks with their name, symbol, current price. Each line represents one stock and each field is separated by comma. The file MUST contain at least 30 stocks. o E.g., Microsoft Corporation, MSFT, 23.34 Google Inc, GOOG, 786.79 Bank of America, BAC, 16.76 AT&T Inc, T, 34.54
You will use interactive I/O in this program. All of the input must be validated if it is needed. You can assume that for a numeric input value, the grader will enter a numeric value in the testing cases.
Output Your program should display the sum and average of the list of stocks, the name of the stock with highest price and the name of the stock with lowest price on the console, and then write them to a file.
This is Assignment 6 that I completed:
SUMMARY: This program simulated the price change in the stock
over time.
*/
(THIS IS ONE JAVA FILE-MAIN)
import java.text.DecimalFormat;
import java.util.*;
//main function and main code
public class HW6{
private static Scanner scan;
public static void main(String[] args) {
//declare set variables
String NameOfStock;
String SymbolofStock;
double YesterdayPrice;
double TodayPrice;
double ChangeInPrice;
double PercentInChange;
int number_of_days = 30;
//scanner
scan = new Scanner(System.in);
Stock sim = new Stock();
DecimalFormat format = new DecimalFormat("#.00");
//get the name of the stock from user
System.out.println("Please enter the name of the stock: ");
NameOfStock = scan.nextLine();
if(NameOfStock.equals("NONE")){
NameOfStock = sim.StockName;
}
//get the symbol of the stock from user
sim.setStockName(NameOfStock);
System.out.println("Please enter the symbol of the stock:");
SymbolofStock = scan.nextLine();
//If the user puts in na it sets the symbol to the default
constructor
if(SymbolofStock.contentEquals("NA")){
SymbolofStock = sim.StockSymbol;
}
sim.setStockSymbol(SymbolofStock);
//get price of stock from user for yesterday
System.out.println("Please enter yesterday's price of " +
NameOfStock + ": ");
YesterdayPrice = scan.nextDouble();
//If the user puts in 0 the programs sets the price to the
default constructor
if(YesterdayPrice == 0){
YesterdayPrice = Stock.YesterdaysPrice;
}
sim.setYesterdayPrice(YesterdayPrice);
System.out.format("%-10s%-11s%-20s%-17s%-19s%-19s\n", "STOCK",
"SYMBOL", "YESTERDAY_PRICE", "TODAY_PRICE", "PRICE_MOVEMENT",
"CHANGE_PERCENT");
//Runs through what the stock will be for 30 days
for(int i = 0; i <= number_of_days; i++){
YesterdayPrice = sim.getYesterdayPrice();
TodayPrice = sim.SimulateStockPrice(YesterdayPrice);
ChangeInPrice = sim.priceDifference(TodayPrice,
YesterdayPrice);
PercentInChange = sim.pricePercentDifference(YesterdayPrice,
TodayPrice);
PercentInChange = Math.round(PercentInChange);
sim.setTodayPrice(TodayPrice);
System.out.format("%-12s%-14s%-18s%-18s%-20s%-22s\n", NameOfStock,
SymbolofStock, format.format(YesterdayPrice),
format.format(TodayPrice), format.format(ChangeInPrice),
format.format(PercentInChange) + "%\n");
}
System.out.println("Goodbye!");
}
}
/*
/*
==========================================================================
*/
/* E N D O F P R O G R A M */
/*
==========================================================================
*/
(OTHER JAVA FILE-STOCK FILE)
/*
* This is the stock file
*/
import java.util.Random;
//stock function and stock code
public class Stock {
//declare set variables
String StockName = "Microsoft";
String StockSymbol = "MSFT";
static double YesterdaysPrice = 46.87;
private double TodaysPrice = 46.87;
//private double ZeroChange = 0;
//private double ZeroChangePercent = 0;
private double Change;
private double PriceNew;
private double DifferenceInPrice;
private double PerecentDifference;
//random generator
Random rand = new Random();
//This stores a value in the field for name
public void setStockName(String n){
if(n == "NONE"){
n = StockName;
}
StockName = n;
}
//This stores a value in the field for symbol
public void setStockSymbol(String s){
StockSymbol = s;
}
//This stores a value in the field for the current price
public void setYesterdayPrice(double cP){
if(cP < 0){
YesterdaysPrice = 0;
}
else
YesterdaysPrice = cP;
}
//This stores a value in the field for the next price
public void setTodayPrice(double nP){
if(nP < 0){
TodaysPrice = 0;
}
else
TodaysPrice = nP;
}
//This returns the stock object's name to the user
public String getStockName(){
return StockName;
}
//This returns the stock object's symbol to the user
public String getStockSymbol(){
return StockSymbol;
}
//This returns the stock object's current price to the user
public double getYesterdayPrice(){
return YesterdaysPrice;
}
//This returns the stock object's next price to the user
public double getTodayPrice(){
return TodaysPrice;
}
//This function calculates the random increase or decrease in the
stock over the next 30 days
public double SimulateStockPrice(double cP){
Change = (Math.random() * ((10 - 0) + 1)) + 0;
Change = Change/100;
if(rand.nextInt(2) == 1){
PriceNew = cP - (cP * Change);
}
else
PriceNew = cP + (cP * Change);
return PriceNew;
}
//This shows the difference between the prices of the stock
public double priceDifference(double cP, double new_price){
DifferenceInPrice = cP - new_price;
return DifferenceInPrice;
}
//This shows the change in a percentage of the stock
public double pricePercentDifference(double cP, double
new_price){
PerecentDifference = ((new_price/cP) * 100) - 100;
if(PerecentDifference < 0){
PerecentDifference = PerecentDifference + (PerecentDifference *
-2);
}
return PerecentDifference;
}
}
//Java Code
public class Stock {
//fields
private String name;
private String symbol;
private double price;
//3 args constructor
public Stock(String name, String symbol, double price) {
this.name = name;
this.symbol = symbol;
setPrice(price);
}
//all getters and setters
/**
*
* @return stock name
*/
public String getName() {
return name;
}
/**
* set stock name
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return symbol
*/
public String getSymbol() {
return symbol;
}
/**
* set symbol of stock
* @param symbol
*/
public void setSymbol(String symbol) {
this.symbol = symbol;
}
/**
*
* @return stock's price
*/
public double getPrice() {
return price;
}
/**
* set price of stock with protection
* against negative value
* @param price
*/
public void setPrice(double price) {
//If price is negative value
if(price<0)
this.price = 0;
else
this.price = price;
}
/**
*
* @return String representation of Stock object
*/
@Override
public String toString() {
return "Stock[" +
"name='" + name + '\'' +
", symbol='" + symbol + '\'' +
", price=" + price +
']';
}
}
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;
public class HW6 {
public static void main(String[] args)
{
try {
//Create an array list of stocks
ArrayList<Stock> stocks = new ArrayList<>();
//Prompt user for input file
Scanner input = new Scanner(System.in);
System.out.print("Enter input file: ");
String inputFileName = input.nextLine();
//open file to read
File myFile = new File(inputFileName);
Scanner inputFile = new Scanner(myFile);
//read all data from file
while (inputFile.hasNextLine())
{
String[] tokens = inputFile.nextLine().trim().split(",");
//Create stock object
Stock stock = new Stock(tokens[0],tokens[1],Double.parseDouble(tokens[2]));
//Add stock to stock list
stocks.add(stock);
}
//Close the file stream
inputFile.close();
//Prompt user for output file
System.out.print("Enter output file name: ");
String outputFileName = input.nextLine();
//Write data to file as well as console
PrintWriter writer = new PrintWriter(new FileWriter(outputFileName));
int index1 = getHighestStockIndex(stocks);
int index2 = getLowestStockIndex(stocks);
DecimalFormat format = new DecimalFormat("#.00");
System.out.println("Sum of Stock Price: $"+format.format(getSum(stocks)));
System.out.println("Average of Stock Price: $"+format.format(getAverage(stocks)));
System.out.println("Highest Price Stock's name: "+stocks.get(index1).getName()+" and its price: $"+format.format(stocks.get(index1).getPrice()));
System.out.println("Lowest Price Stock's name: "+stocks.get(index2).getName()+" and its price: $"+format.format(stocks.get(index2).getPrice()));
writer.println("Sum of Stock Price: $"+format.format(getSum(stocks)));
writer.println("Average of Stock Price: $"+format.format(getAverage(stocks)));
writer.println("Highest Price Stock's name: "+stocks.get(index1).getName()+" and its price: $"+format.format(stocks.get(index1).getPrice()));
writer.println("Lowest Price Stock's name: "+stocks.get(index2).getName()+" and its price: $"+format.format(stocks.get(index2).getPrice()));
//close output stream
writer.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
/**
*
* @param stocks
* @return sum of stocks price
*/
public static double getSum(ArrayList<Stock> stocks)
{
double sum =0;
for (Stock s:stocks)
{
sum += s.getPrice();
}
return sum;
}
/**
*
* @param stocks
* @return average of stock price
*/
public static double getAverage(ArrayList<Stock>stocks)
{
return getSum(stocks)/stocks.size();
}
/**
*
* @param stocks
* @return highest stock index
*/
public static int getHighestStockIndex(ArrayList<Stock>stocks)
{
int index = 0;
double price = stocks.get(0).getPrice();
for (int i = 0; i < stocks.size(); i++) {
if(price<stocks.get(i).getPrice())
{
price = stocks.get(i).getPrice();
index=i;
}
}
return index;
}
/**
*
* @param stocks
* @return lowest stock index
*/
public static int getLowestStockIndex(ArrayList<Stock>stocks)
{
int index = 0;
double price = stocks.get(0).getPrice();
for (int i = 0; i < stocks.size(); i++) {
if(price>stocks.get(i).getPrice())
{
price = stocks.get(i).getPrice();
index=i;
}
}
return index;
}
}
//input file
//output file
//Output
//If you need any help regarding this solution..... please leave a comment...... thanks