Question

I am a beginner when it comes to java codeing. Is there anyway this code can...

I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding?

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

Homework Answers

Answer #1

No, this code is perfectly working and is as simple as it could be..

The first class i.e Stock has three private variable name,symbol and price.

As all the members are private getter and setters are provided to access the elements and tostring method to print the attributes.

A three parameter constructor to initialize values to attributes during object creation.

In the second class, i.e HW6

An arraylist of stock is created.

An input file is used as data to run the program. In the input file , for every stock the data is sperated by ',' . i.e name,symbol,price.

The file is read line by line and is spllited in parts using "," as token.

All the datas are loaded in the arraylist and average, sum, highest and lowest stock is written to an output file and also to the program console.

For calculating sum,average, highest and lowest static functions are provided for each.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
THIS IS FOR JAVA I have to write a method for a game of Hangman. The...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The word the user is trying to guess is made up of hashtags like so " ###### " If the user guesses a letter correctly then that letter is revealed on the hashtags like so "##e##e##" If the user guesses incorrectly then it increments an int variable named count " ++count; " String guessWord(String guess,String word, String pound) In this method, you compare the character(letter)...
Hello, I am trying to create a Java program that reads a .txt file and outputs...
Hello, I am trying to create a Java program that reads a .txt file and outputs how many times the word "and" is used. I attempted modifying a code I had previously used for counting the total number of tokens, but now it is saying there is an input mismatch. Please help! My code is below: import java.util.*; import java.io.*; public class Hamlet2 { public static void main(String[] args) throws FileNotFoundException { File file = new File("hamlet.txt"); Scanner fileRead =...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public void addStudent(String student) {         if (numberOfStudents == students.length) {             String[] a = new String[students.length + 1];            ...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
I wrote the following java code with the eclipse ide, which is supposed to report the...
I wrote the following java code with the eclipse ide, which is supposed to report the number of guesses it took to guess the right number between one and five. Can some repost the corrected code where the variable "guess" is incremented such that the correct number of guesses is displayed? please test run the code, not just look at it in case there are other bugs that exist. import java.util.*; public class GuessingGame {    public static final int...
I am writing code in java to make the design below. :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) I already have...
I am writing code in java to make the design below. :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) :-):-):-):-):-):-)  :-):-):-):-):-):-)  :-):-):-):-):-):-) I already have this much public class Main { int WIDTH = 0; double HEIGHT = 0; public static void drawSmileyFaces() { System.out.println(" :-):-):-):-):-):-)"); } public static void main (String[] args) { for (int WIDTH = 0; WIDTH < 3; WIDTH++ ) { for(double HEIGHT = 0; HEIGHT < 2; HEIGHT++) { drawSmileyFaces(); } } } } I am pretty sure that alot of this is wrong...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
Provide A UML for the Following CODE public class Employee{ public String strName, strSalary; public Employee(){...
Provide A UML for the Following CODE public class Employee{ public String strName, strSalary; public Employee(){    strName = " ";    strSalary = "$0";    } public Employee(String Name, String Salary){    strName = Name;    strSalary = Salary;    } public void setName(String Name){    strName = Name;    } public void setSalary(String Salary){    strSalary = Salary;    } public String getName(){    return strName;    } public String getSalary(){    return strSalary;    } public String...
This is the java code that I have, but i cannot get the output that I...
This is the java code that I have, but i cannot get the output that I want out of it. i want my output to print the full String Form i stead of just the first letter, and and also print what character is at the specific index instead of leaving it empty. and at the end for Replaced String i want to print both string form one and two with the replaced letters instead if just printing the first...
JAVA public class Purchase { private String name; private int groupCount; //Part of price, like the...
JAVA public class Purchase { private String name; private int groupCount; //Part of price, like the 2 in 2 for $1.99. private double groupPrice; //Part of price, like the $1.99 in 2 for $1.99. private int numberBought; //Total number being purchased. public Purchase () { name = "no name"; groupCount = 0; groupPrice = 0; numberBought = 0; } public Purchase (String name, int groupCount, double groupPrice, int numberBought) { this.name = name; this.groupCount = groupCount; this.groupPrice = groupPrice; this.numberBought...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT
Active Questions
  • Statistics Discussion: The accuracy of a forecasting technique is evaluated especially using the MSE (mean squared...
    asked 21 minutes ago
  • If the U.S. government manages to close a recessionary gap and achieve potential GDP with fiscal...
    asked 25 minutes ago
  • A block with mass 10kg is on a ramp angled at 20 degrees above the horizontal,...
    asked 25 minutes ago
  • I have a sample of 31 7thgrade girls who took an IQ test.  I calculated the sample...
    asked 33 minutes ago
  • A researcher wishes to estimate the proportion of adults who have​ high-speed Internet access. What size...
    asked 33 minutes ago
  • Brick column in the external corridor of a house, with section size of 440 mm X520...
    asked 34 minutes ago
  • 17.                             Mel has a(n) __________ lien on Ellen’s car after he replaced her clutch. The lien.
    asked 41 minutes ago
  • Jackson Company engaged in the following investment transactions during the current year. Feb 17,Purchased  430 shares of...
    asked 52 minutes ago
  • When might discrimination in the workplace be justified? Might discrimination on the basis of gender or...
    asked 1 hour ago
  • The strength grade of materials used for brick masonry at a certain site is as follows:...
    asked 1 hour ago
  • Show (prove), from the original definition of the integers, that subtraction of integers is well defined....
    asked 1 hour ago
  • How is polarity of a "bond" different than polarity of a "molecule?" What makes a particular...
    asked 1 hour ago