Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Write a program that asks the user to enter the name, opening price, closin

ID: 3870222 • Letter: J

Question

Java

Write a program that asks the user to enter the name, opening price, closing price, and number of shares owned for a stock. Have the program compute the current value of the stock (hint: closing value time number of shares owned) and the amount gained or lost. Display the stock name, opening price, closing price, number of shares, opening value, closing value, and the gain/loss. Additionally, you will ask the user for a file to write the data to.

Create an “if” statement that tells the user whether the stock has gained or lost value based on the gain/loss (see example below).

Data validation: Ensure the user enters values greater than zero for the opening price, closing price and number of shares. Give an error statement if invalid. Use a “priming read” to do this (if necessary).

Loops: encapsulate all of the above in a loop that asks if the user wants to enter another stock and continues to run as long as the user answers “yes” (remember to use the proper string comparison technique).

Use String.format or DecimalFormat to format the output as shown in the following example to both the screen/dialog box and the file the user specified:

Stock: MSFT
Opening Price: $30.00
Closing Price: $35.00
Number of Shares: 1000
Opening Value: $30,000.00
Closing Value: $35,000.00
Gain/Loss: Your portfolio gained $5,000.00 in value

Explanation / Answer

import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.Scanner; import java.io.FileWriter; import java.io.BufferedWriter; public class Stocks { public static void main(String args[]) { String userResponse = ""; FileWriter fWriter = null; BufferedWriter writer = null; //Setting the decimal formatting DecimalFormat df = new DecimalFormat(); df.setMinimumFractionDigits(2); df.setMaximumFractionDigits(2); Scanner keyboard = new Scanner(System.in); System.out.println("Please enter the path of file to write to:"); try { File file = new File(keyboard.nextLine()); fWriter = new FileWriter(file); writer = new BufferedWriter(fWriter); String stockName; double openPrice, closePrice; int numberOfShares; do{ // Start taking and validating user input System.out.println("Please enter the Name of the stock"); stockName = keyboard.nextLine(); System.out.println("Please enter the opening price"); openPrice = keyboard.nextDouble(); while (openPrice
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote