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)...
[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...
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];            ...
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 =...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list code and can't figure out how to complete it: Below is the code Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class. /////////////////////////////////////////////////////////////////////////////////////////////////////////// Grocery Class (If this helps) package Shopping; public class Grocery implements Comparable<Grocery> { private String name; private String category; private int aisle; private float price; private int quantity;...
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...
What's wrong with this code? #Java Why I am getting error in : int BusCompare =...
What's wrong with this code? #Java Why I am getting error in : int BusCompare = o1.numberOfBusinesses.compareTo(o2.numberOfBusinesses); public class TypeComparator implements Comparator<Type> { @Override public int compare(Type o1, Type o2) { // return o1.name.compareTo(o2.name); int NameCompare = o1.name.compareTo(o2.name); int BusCompare = o1.numberOfBusinesses.compareTo(o2.numberOfBusinesses); // 2-level comparison using if-else block if (NameCompare == 0) { return ((BusCompare == 0) ? NameCompare : BusCompare); } else { return NameCompare; } } } public class Type implements Comparable<Type> { int id; String name; int...
I have a 2 class code and it works everything is fine and runs as it...
I have a 2 class code and it works everything is fine and runs as it supposed too. What will the UML be for both classes. Here's the code, any help will be awsome, Thanks. import java.util.Scanner; public class PayRollDemo { public static void main(String[] args) { double payRate; int hours; PayRoll pr = new PayRoll(); Scanner keyboard = new Scanner(System.in); for (int index = 0; index < 7 ; index++ ) { System.out.println(); System.out.println("EmployeeID:" + pr.getEmployeeID(index)); System.out.println(); System.out.println("Enter the...
How do I make this: public class Country {     private String name;     private double area;     private...
How do I make this: public class Country {     private String name;     private double area;     private int population;     public Country(String name, double area, int population) {         this.name = name;         this.area = area;         this.population = population;     }     public double getPopulationDensity() {         return population / area;     }     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     public double getArea() {         return area;     }     public void setArea(double area) {         this.area = area;     }     public int getPopulation()...
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...