Question

In: Computer Science

You are required to read in a list of stocks from a text file “stocks.txt” and...

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;
}
}

Solutions

Expert Solution

//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


Related Solutions

Problem Statement You are required to read in a list of stocks from a text file...
Problem Statement 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...
How to read a text file and store the elements into a linked list in java?...
How to read a text file and store the elements into a linked list in java? Example of a text file: CS100, Intro to CS, John Smith, 37, 100.00 CS200, Java Programming, Susan Smith, 35, 200.00 CS300, Data Structures, Ahmed Suad, 41, 150.50 CS400, Analysis of Algorithms, Yapsiong Chen, 70, 220.50 and print them out in this format: Course: CS100 Title: Intro to CS Author: Name = John Smith, Age = 37 Price: 100.0. And also to print out the...
This is a python file Reads information from a text file into a list of sublists....
This is a python file Reads information from a text file into a list of sublists. Be sure to ask the user to enter the file name and end the program if the file doesn’t exist. Text file format will be as shown, where each item is separated by a comma and a space: ID, firstName, lastName, birthDate, hireDate, salary Store the information into a list of sublists called empRoster. EmpRoster will be a list of sublists, where each sublist...
Complete the program to read in values from a text file. The values will be the...
Complete the program to read in values from a text file. The values will be the scores on several assignments by the students in a class. Each row of values represents a specific student's scores. Each column represents the scores of all students on a specific assignment. So a specific value is a specific student's score on a specific assignment. The first two values in the text file will give the number of students (number of rows) and the number...
Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
Design a program that will read each line of text from a file, print it out...
Design a program that will read each line of text from a file, print it out to the screen in forward and reverse order and determine if it is a palindrome, ignoring case, spaces, and punctuation. (A palindrome is a phrase that reads the same both forwards and backwards.) Example program run: A Toyota's a Toyota atoyoT a s'atoyoT A This is a palindrome! Hello World dlroW olleH This is NOT a palindrome! Note: You are only designing the program...
In Java. Modify the attached GameDriver2 to read characters in from a text file rather than...
In Java. Modify the attached GameDriver2 to read characters in from a text file rather than the user. You should use appropriate exception handling when reading from the file. The text file that you will read is provided. -------------------- Modify GaveDriver2.java -------------------- -----GameDriver2.java ----- import java.io.File; import java.util.ArrayList; import java.util.Scanner; /** * Class: GameDriver * * This class provides the main method for Homework 2 which reads in a * series of Wizards, Soldier and Civilian information from the user...
HW_6b - Read and write a text file. Include the following in the main.cpp file. Add...
HW_6b - Read and write a text file. Include the following in the main.cpp file. Add code so that the numbers that are read from the data.txt file are written to an output           file named:   results.txt After the numbers are written to the file, the following message should be displayed:    The data has been written to the file. Open the results.txt file and verify that the file was written successfully. Please make the code based on C++,...
Prior to beginning work on this discussion, read the required chapters from the text and review...
Prior to beginning work on this discussion, read the required chapters from the text and review the required articles for this week. Alcohol and caffeine have nearly opposite effects on behavior and the nervous system, yet these substances are not used to treat overdose or addiction to the other. Why not use caffeine to treat alcohol addiction? Analyze the issues of pharmacological and physiological antagonism. Explain the receptor systems involved and the central nervous system structures effects with regard to...
In this lab, you open a file and read input from that file in a prewritten...
In this lab, you open a file and read input from that file in a prewritten C++ program. The program should read and print the names of flowers and whether they are grown in shade or sun. The data is stored in the input file named flowers.dat. Instructions Ensure the source code file named Flowers.cpp is open in the code editor. Declare the variables you will need. Write the C++ statements that will open the input file flowers.dat for reading....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT