Question

In: Computer Science

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

Assignment 6
You are required to write a stock price simulator, which simulates a price change of a stock.
When the program runs, it should do the following:
 Create a Stock class which must include fields: name, symbol, currentPrice, nextPrice,
priceChange, and priceChangePercentage.
 The Stock class must have two constructor: a no-argument constructor and a constructor
with four parameters that correspond to the four fields.
o For the no-argument constructor, set the default value for each field such as:
 Name: Microsoft
 Symbol: MSFT
 currentPrice: 46.87
 nextPrice: 46.87
o For the argument constructor, set the value of four fields based on the arguments.
 The Stock class must have accessors and mutators for all of its fields.
 The setter methods must protect a user from setting the currentPrice/nextPrice into
negative number. You can set the values to 0 if a user tries to change them to negative
values.
 The Stock class should have a SimulatePrice() method, which increases or decreases the
currentPrice by 0 - 10% randomly, including 0.00% and 2.34%.
 The main program will ask user to enter a name, symbol, current price of a stock. Then, it
simulates the prices for next 30 days. It displays the prices for the next 30 days on the
console. If a user enters “NONE”, “NA”, 0.0 for name, symbol, current price
respectively, then the no-argument constructor is used. Input
This program requires that you read in the following data values:
 A stock’s name, symbol, and current price.
o E.g., Microsoft Corporation, MSFT, 45.87.
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 stock’s name, symbol, current price, next price
priceChange, and priceChangePercentage for each day on the console.
Test case output: (green texts are user input)
Please enter the name of the stock: Microsoft
Please enter the symbol of the stock: MSFT
Please enter yesterday's price of Microsoft: 45.65
STOCK SYMBOL YESTERDAY_PRICE TODAY_PRICE PRICE_MOVEMENT CHANGE_PERCENT
Microsoft MSFT 45.65 47.48 1.83 4.00%
Microsoft MSFT 47.48 52.22 4.75 10.00%
Microsoft MSFT 52.22 49.61 -2.61 -5.00%
Microsoft MSFT 49.61 47.13 -2.48 -5.00%
Microsoft MSFT 47.13 51.84 4.71 10.00%
Microsoft MSFT 51.84 57.03 5.18 10.00%
Microsoft MSFT 57.03 54.18 -2.85 -5.00%
Microsoft MSFT 54.18 59.05 4.88 9.00%
Microsoft MSFT 59.05 62.01 2.95 5.00%
Microsoft MSFT 62.01 57.05 -4.96 -8.00%
Microsoft MSFT 57.05 54.19 -2.85 -5.00%
Microsoft MSFT 54.19 49.32 -4.88 -9.00%
Microsoft MSFT 49.32 46.85 -2.47 -5.00%
Microsoft MSFT 46.85 50.60 3.75 8.00%
Microsoft MSFT 50.60 55.15 4.55 9.00%
Microsoft MSFT 55.15 58.46 3.31 6.00%
Microsoft MSFT 58.46 61.38 2.92 5.00%
Microsoft MSFT 61.38 55.86 -5.52 -9.00%
Microsoft MSFT 55.86 56.42 0.56 1.00%
Microsoft MSFT 56.42 56.98 0.56 1.00%
Good bye!

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


Related Solutions

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...
C++ Parse text (with delimiter) read from file. If a Text file has input formatted such...
C++ Parse text (with delimiter) read from file. If a Text file has input formatted such as: "name,23" on every line where a comma is the delimiter, how would I separate the string "name" and integer "23" and set them to separate variables for every input of the text file? I am trying to set a name and age to an object and insert it into a vector. #include <iostream> #include <vector> #include <fstream> using namespace std; class Student{    ...
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...
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...
PROBLEM STATEMENT: Using the list container from the STL, write a program that will read the...
PROBLEM STATEMENT: Using the list container from the STL, write a program that will read the information from a file into a list and then display the list to the screen. Add your name. Sort the list by id. Print the list again CODE: Use the provided disneyin2.txt file. Do not hard code the file name; get file name from user. Use the struct below struct student { char firstnm[20], lastnm[20]; int id, grade; }; You are to create a...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT