Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Part 1 - Singly Linked Lists and the Dow Jones Industrial Average In lecture our singly linked lists have not been ordered in any particular

Part 1 - Singly Linked Lists and the Dow Jones Industrial Average

In lecture our singly linked lists have not been ordered in any particular way. Now, we are going to define a list managing class that that will manage DJIACompany objects (DJIA is short for Dow Jones Industrial Average) that ensures that every node is added to the list in its proper location such that our list is always sorted by company ticker symbol.

Note that part one has four source files. Go through the code of these files and read the documentation. DJIAApp has a main method and so is an app that will run and open up a user interface to demonstrate use of your list. You will write code inside DJIASortedList, which when defined properly will allow you to see the rendering of your list (how exciting).

The list that you are going to build will represent the Dow Jones Industrial Average(https://www.marketwatch.com/investing/index/djia), which is a strange, if not silly calculation using the stock prices of 30 carefully selected companies and a mysterious divisor. To calculate the DOW, you add up the stock prices of the 30 companies and divide that number by the divisor.

YOUR FOUR METHODS, ALL FROM THE DJIASortedList CLASS

Define the addToSortedData method such that it adds the dataToAdd argument to the list in the proper sorted location according to ticker symbol. If a company is already in the list with this ticker symbol, it is not added. There can only be one of each company in this list.

Define the clear method such that it when called it completely empties the list of all nodes.

Define the computeDJIA method such that it adds up the stock prices of all 30 companies and divides it by the divisor, returning this value. If the list does not have 30 companies, 0 is returned.

Define the getTopDJIAContributor method such that it looks at the companies in the list and finds the one with the largest impact on the DOW. This means it has the largest stock price per share. If the list does not have 30 companies, null is returned.

Should you load all 30 DJIA elements into the list, then hit the "Which DJIA Company affects the DJIA the most?" button, it should tell you BA (i.e. Boeing Aircraft), at least it would today. If Boeing's stock price were to plummet that would change. Note that you should be careful to test your list using all sorts of combinations of behavior. Add all the stocks then clear then add them back then clear the add them then compute the DOW average. Software is never single use, it's always combinations of use that can trip up code.

Should you load all 30 DJIA elements into the list, then hit the "Calculate DJIA" button it should look like the graphic below. Note that we are using DOW data as of January 24th of this year.

Here is code.

package part_one_djia;

import java.io.*; import java.text.*; import java.util.*; import javafx.application.Application; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.stage.Screen; import javafx.stage.Stage;

/** * DJIAApp.java * * DO NOT CHANGE THIS FILE. * * This class plays around with a DJIASortedList of DJIACompany objects. * It uses methods in that list class to manipulate and calculate the * Dow Jones Industrial Average, which is a measure of the New York * Stock Market's performance, a rather dumb one I might add. * * This file is used in Part 1 of HW 2. In this part, you only need to * define the necessary methods inside the DJIASortedList class. * */ public class DJIAApp extends Application { // HERE'S THE LIST WE'RE GOING TO PLAY AROUND WITH DJIASortedList list = new DJIASortedList();

// THIS IS THE WINDOW AND IT'S TOP LEVEL PANE Stage primaryStage; BorderPane primaryPane = new BorderPane(); Scene primaryScene = new Scene(primaryPane);

// NORTH TOOLBAR HBox topPane = new HBox(); Button addButton = makeButton("Add Company"); Button calculateButton = makeButton("Calculate DJIA"); Button emptyListButton = makeButton("Empty the List"); Button getBiggestContributorButton = makeButton("Which DJIA Company affects the DJIA the most?");

// THIS WILL RENDER OUR LIST StackPane centerPane = new StackPane(); DJIACanvas djiaCanvas = new DJIACanvas(list);

// THIS IS FOR READING DJIA DATA FROM A FILE BufferedReader reader;

/** * Default Constructor, it sets up the GUI. */ public void start(Stage initPrimaryStage) { // SETUP THE WINDOW primaryStage = initPrimaryStage; primaryStage.setScene(primaryScene); primaryStage.setTitle("The Dow Jones Industrial Average App");

// INIT THE GUI layoutGUI(); initFileReader();

// OPEN THE WINDOW primaryStage.show(); } /** * Helper method for making a simple textual button. */ private Button makeButton(String text) { Button b = new Button(text); b.setStyle("-fx-font-size:14pt; -fx-padding:10px; -fx-border-radius:50"); return b; }

/** * This method initializes a text file reader so that the * Dow Jones Industrial Average (DJIA) data can be read in * and used. */ private void initFileReader() { // SETUP THE READER SO IT CAN READ DATA WHEN NEEDED String fileName = "DJIA.txt"; try { // OPEN A STREAM TO THE FILE FileInputStream fis = new FileInputStream(fileName); InputStreamReader isr = new InputStreamReader(fis); reader = new BufferedReader(isr);

// GET THE DIVISOR String line = reader.readLine(); list.setDivisor(Double.parseDouble(line)); } catch (IOException ioe) { // THE DJIA.txt FILE WAS NOT FOUND, IT MIGHT BE IN THE WRONG DIRECTORY Alert dialog = new Alert(AlertType.ERROR); dialog.setTitle("File Not Found"); dialog.setHeaderText(null); dialog.setContentText(fileName + " not found"); } }

/** * Layout the buttons and other GUI components. */ private void layoutGUI() { // SETUP THE TOP TOOLBAR topPane.setAlignment(Pos.CENTER); topPane.getChildren().add(addButton); topPane.getChildren().add(calculateButton); topPane.getChildren().add(emptyListButton); topPane.getChildren().add(getBiggestContributorButton);

// THE CENTER ONLY HAS THE CANVAS centerPane.getChildren().add(djiaCanvas); djiaCanvas.widthProperty().bind(centerPane.widthProperty()); djiaCanvas.heightProperty().bind(centerPane.heightProperty());

// MAKE THE WINDOW FIT OUR SCREEN Screen screen = Screen.getPrimary(); Rectangle2D bounds = screen.getVisualBounds(); primaryStage.setX(bounds.getMinX()); primaryStage.setY(bounds.getMinY()); primaryStage.setWidth(bounds.getWidth()); primaryStage.setHeight(bounds.getHeight());

// PUT EVERYTHING IN OUR MAIN PANE primaryPane.setTop(topPane); primaryPane.setCenter(centerPane);

// SETUP EVENT HANDLERS addButton.setOnAction(e -> { respondToAdd(); }); calculateButton.setOnAction(e -> { respondToCalculate(); }); emptyListButton.setOnAction(e -> { respondToEmpty(); }); getBiggestContributorButton.setOnAction(e -> { respondToGetBiggestContributor(); }); }

/** * Helper method for displaying a simple message dialog. */ private void showMessageDialog(AlertType alertType, String title, String message) { Alert dialog = new Alert(alertType); dialog.setTitle(title); dialog.setHeaderText(null); dialog.setContentText(message); dialog.showAndWait(); }

/** * Handles when the user presses the button to add a company.. */ public void respondToAdd() { try { // GET THE NEXT COMPANY String line = reader.readLine(); // HANDLE ERROR FEEDBACK if (line == null) { showMessageDialog(AlertType.WARNING, "End of Data", "No more data to read"); } else { // PARSE THE INFORMATION AND DISPLAY StringTokenizer st = new StringTokenizer(line, ","); String name = st.nextToken(); String symbol = st.nextToken(); double price = Double.parseDouble(st.nextToken()); DJIACompany company = new DJIACompany(name, symbol, price); list.addToSortedData(company); djiaCanvas.repaint(); } } catch (IOException ioe) { // ERROR FEEDBACK showMessageDialog(AlertType.WARNING, "Error Reading File", "There was an error reading the DJIA data file"); } }

/** * Handles when the user presses the calculate the DOW * button. */ private void respondToCalculate() { // ONLY DO IT IF WE HAVE ALL 30 COMPANIES LOADED if (list.size() < 30) { // GIVE ERROR FEEDBACK showMessageDialog(AlertType.WARNING, "Finish Adding First", "You must add all 30 DOW Components first"); } else { // GET THE CALCULATION AND DISPLAY IT double djia = list.computeDJIA(); NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(1); nf.setMinimumFractionDigits(1); String djiaText = "Current DJIA: " + nf.format(djia) + " Points"; showMessageDialog(AlertType.WARNING, "Current DJIA", djiaText); } }

/** * Handles when the user presses the empty button, which * should reset everything, including both the list and the * canvas. */ private void respondToEmpty() { // CLEAR THE LIST list.clear(); // REST FOR RE-READING THE FILE initFileReader(); // CLEAR THE CANVAS djiaCanvas.repaint(); }

/** * Handles when the user presses the get biggest * contributor button, which will figure out which * stock makes the biggest contribution. */ private void respondToGetBiggestContributor() { // ONLY DO THIS IF WE HAVE ALL 30 STOCKS if (list.size() < 30) { showMessageDialog(AlertType.WARNING, "List Incomplete", "List Not Yet Full"); } else { // GET AND DISPLAY THE ANSWER String text = list.getTopDJIAContributor().getSymbol(); text += " has the biggest impact on the DJIA"; showMessageDialog(AlertType.INFORMATION, "Biggest Contributor?", text); } }

/** * The main method launches our JavaFX application. */ public static void main(String[] args) { launch(args); } }

package part_one_djia;

import java.util.Iterator; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight;

/** * DJIACanvas.java * * DO NOT CHANGE THIS FILE * * This class does the rendering of the list of Dow Jones * Industrial Average components in a list. * */ public class DJIACanvas extends Canvas { // THIS IS THE LIST WE'LL BE DRAWING DJIASortedList list;

// THESE ARE ALL THE DRAWING CONSTANTS int TEXT_Y_OFFSET = 20; int TEXT_X_OFFSET = 5; int RECT_WIDTH = 120; int RECT_HEIGHT = 50; int RECT_X_OFFSET = 30; int RECT_Y_OFFSET = 50; int NODES_PER_ROW = 6; int MAX_NODES = 30; int ARROW_TAIL_LENGTH = 10; int NODES_PER_COLUMN = MAX_NODES / NODES_PER_ROW; Font nodeFont = Font.font("Helvetica", FontWeight.NORMAL, FontPosture.REGULAR, 16);

/** * Constructor keeps the list for later. * * @param initList List of DJIA companies to draw. */ public DJIACanvas(DJIASortedList initList) { list = initList; } /** * This function clears the canvas and then does * the rendering, this is to be called each time * the list is changed. */ public void repaint() { // THIS DOES THE ACTUAL RENDERING GraphicsContext gC = getGraphicsContext2D(); gC.setFont(nodeFont);

// WHAT ARE THE PANEL DIMENSIONS int canvasWidth = (int) getWidth(); int canvasHeight = (int) getHeight();

// CLEAR OUT WHAT WE DREW PREVIOUSLY gC.clearRect(0, 0, canvasWidth, canvasHeight);

// CALCULATE THE SIZE OF EVERYTHING WE NEED TO DRAW int totalWidth = (NODES_PER_ROW * RECT_WIDTH) + ((NODES_PER_ROW - 1) * RECT_X_OFFSET); int totalHeight = ((NODES_PER_COLUMN + 2) * RECT_HEIGHT) + ((NODES_PER_COLUMN + 1) * RECT_Y_OFFSET); int arrowX1, arrowY1, arrowX2, arrowY2;

// CALCULATE THE PANEL LOCATION OF THE FIRST NODE int rectX = (canvasWidth / 2) - (totalWidth / 2); int rectY = (canvasHeight / 2) - (totalHeight / 2) + RECT_HEIGHT;

// DRAW THE "head" int headX = rectX - RECT_X_OFFSET - RECT_WIDTH + TEXT_X_OFFSET; int headY = rectY + TEXT_Y_OFFSET; gC.strokeText("head", headX, headY);

// CALCULATE THE COORDINATES FOR THE LINE FROM THE head int headX1 = headX + (RECT_WIDTH / 2); int headY1 = rectY + (RECT_HEIGHT * 2 / 3); int headX2 = rectX; int headY2 = headY1; arrowX1 = headX2 - ARROW_TAIL_LENGTH; arrowY1 = headY2 - ARROW_TAIL_LENGTH; arrowX2 = headX2 - ARROW_TAIL_LENGTH; arrowY2 = headY2 + ARROW_TAIL_LENGTH;

// DRAW THE LINE FROM THE head TO THE FIRST NODE gC.strokeLine(headX1, headY1, headX2, headY2); gC.strokeLine(headX2, headY2, arrowX1, arrowY1); gC.strokeLine(headX2, headY2, arrowX2, arrowY2);

// AND NOW DRAW THE REST OF THE NODES int x1, y1, x2, y2, row; boolean drawingComplete = false; int counter = 0; Iterator it = list.listIterator(); while (!drawingComplete) { // IS IT THE END OF THE LIST? if (!it.hasNext()) { drawingComplete = true; gC.strokeText("null", rectX + TEXT_X_OFFSET, rectY + TEXT_Y_OFFSET); } else { // GET THE COMPANY TO DRAW DJIACompany company = (DJIACompany) it.next(); // FIRST THE RECTANGLE gC.strokeRect(rectX, rectY, RECT_WIDTH, RECT_HEIGHT); gC.strokeText(company.toString(), rectX + TEXT_X_OFFSET, rectY + TEXT_Y_OFFSET); counter++;

// AND THEN FIGURE OUT SOME THINGS FOR THE LINES x1 = rectX + (RECT_WIDTH / 2); y1 = rectY + (RECT_HEIGHT * 2 / 3); row = counter / NODES_PER_ROW; if ((counter % NODES_PER_ROW) == 0) { rectY += RECT_HEIGHT + RECT_Y_OFFSET; x2 = x1; y2 = rectY; arrowX1 = x2 - ARROW_TAIL_LENGTH; arrowY1 = y2 - ARROW_TAIL_LENGTH; arrowX2 = x2 + ARROW_TAIL_LENGTH; arrowY2 = y2 - ARROW_TAIL_LENGTH; } else if (row % 2 == 0) { rectX += RECT_WIDTH + RECT_X_OFFSET; x2 = rectX; y2 = y1; arrowX1 = x2 - ARROW_TAIL_LENGTH; arrowY1 = y2 - ARROW_TAIL_LENGTH; arrowX2 = x2 - ARROW_TAIL_LENGTH; arrowY2 = y2 + ARROW_TAIL_LENGTH; } else { rectX -= RECT_WIDTH + RECT_X_OFFSET; x2 = rectX + RECT_WIDTH; y2 = y1; arrowX1 = x2 + ARROW_TAIL_LENGTH; arrowY1 = y2 - ARROW_TAIL_LENGTH; arrowX2 = x2 + ARROW_TAIL_LENGTH; arrowY2 = y2 + ARROW_TAIL_LENGTH; }

// DRAW THE LINE ARROW gC.strokeLine(x1, y1, x2, y2); gC.strokeLine(x2, y2, arrowX1, arrowY1); gC.strokeLine(x2, y2, arrowX2, arrowY2); } } } }

package part_one_djia;

import java.text.NumberFormat;

/** * DJIACompany.java * * DO NOT CHANGE THIS FILE. * * This class represents a single company that is part of the Dow Jones * Industrial Average. Note that there are exactly 30 companies on the DOW. For * a list of all the companies on the DOW, see * https://www.marketwatch.com/investing/index/djia */ public class DJIACompany implements Comparable { // COMPANY NAME private String name;

// TICKER SYMBOL private String symbol;

// STOCK PRICE private double pricePerShare;

/** * Constructor initializes all data. */ public DJIACompany( String initName, String initSymbol, double initPricePerShare) { name = initName; symbol = initSymbol; pricePerShare = initPricePerShare; }

/** * Returns a textual representation of this company, * summarizing its data in a neat format. */ public String toString() { NumberFormat nf = NumberFormat.getCurrencyInstance(); String symbolColumn = symbol; while (symbolColumn.length() < 5) { symbolColumn = " " + symbolColumn; } String priceColumn = nf.format(pricePerShare); while (priceColumn.length() < 10) { priceColumn = " " + priceColumn; } return symbolColumn + priceColumn; }

// ACCESSOR METHODS public String getName() { return name; }

public String getSymbol() { return symbol; }

public double getPricePerShare() { return pricePerShare; }

// MUTATOR METHODS public void setName(String initName) { name = initName; }

public void setSymbol(String initSymbol) { symbol = initSymbol; }

public void setPricePerShare(double initPricePerShare) { pricePerShare = initPricePerShare; }

/** * We only want to compare companies by their ticker symbol * for the purpose of keeping them sorted. */ public int compareTo(Object obj) { DJIACompany otherStock = (DJIACompany) obj; return symbol.compareTo(otherStock.symbol); } }

package part_one_djia;

import java.util.Iterator;

/** * DJIASortedList.java * * YOU MUST FILL IN THE CODE FOR THE FOLLOWING FOUR METHODS: * - addToSortedData * - clear * - computeDJIA * - getTopDJIAContributor * * This class manages a singly linked list of DJIACompany objects * sorted by their ticker symbol. */ public class DJIASortedList { // WE'LL USE A head & A tail private DJIANode head = null; private DJIANode tail = null;

// THIS KEEPS TRACK OF THE NUMBER OF ELEMENTS IN THE LIST, // MAKE SURE YOU UPDATE THIS WHEN NECESSARY private int size = 0;

// THIS IS THE DJIA divisor, A MYSTERIOUS NUMBER private double divisor;

/** * Default constructor, it does nothing */ DJIASortedList() {}

// ACCESSOR METHODS public int size() { return size; }

public double getDivisor() { return divisor; }

// MUTATOR METHOD public void setDivisor(double initDivisor) { divisor = initDivisor; }

/** * You must define this. * * This method adds dataToAdd to the list * in the proper sorted location according to ticker symbol. * If a company is already in the list with this ticker symbol, * it is not added. There can only be one of each company in this * list. */ public void addToSortedData(DJIACompany dataToAdd) { // ADD YOUR CODE HERE }

/** * You must define this. * * This method empties the entire list * and its nodes. */ public void clear() { // ADD YOUR CODE HERE }

/** * You must define this method. * * This method should only perform this calculation if the * list has 30 different companies. It adds up the stock * price of all the companies and divides that total by * the divisor. */ public double computeDJIA() { // ADD YOUR CODE HERE return 0.0; }

/** * You must define this method * * This method looks at the companies in the list and finds * the one with the largest impact on the DOW. This means it * has the largest stock price per share. If the list does not * have 30 companies, null is returned. */ public DJIACompany getTopDJIAContributor() { // ADD YOUR CODE HERE return null; }

/** * DO NOT CHANGE THIS METHOD * * Simple Iterator for getting each item in the list. */ public Iterator listIterator() { return new SortedGenericListIterator(); }

/** * This Iterator goes through the linked list to help * us with drawing it. */ class SortedGenericListIterator implements Iterator { // ITERATOR ALWAYS STARTS AT THE FIRST NODE private DJIANode traveller = head;

public SortedGenericListIterator() {}

/** * Is there another element for the Iterator * to return? */ public boolean hasNext() { if (traveller == null) { return false; } else { return true; } }

/** * Get the next element in the Iterator. */ public Object next() { if (traveller == null) { return null; } Object dataToReturn = traveller.data; traveller = traveller.next; return dataToReturn; }

// TO MAKE THE COMPILER HAPPY, WE WON'T USE IT public void remove() {} }

// THIS NODE CLASS STORES DJIACompany OBJECT DATA ONLY class DJIANode { protected DJIACompany data; protected DJIANode next;

public DJIANode(DJIACompany initData, DJIANode initNext) { data = initData; next = initNext; } } }

Thank you for reading, and help me.

Have a nice day!!! :)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Intelligent Information And Database Systems Asian Conference Aciids 2012 Kaohsiung Taiwan March 19 21 2012 Proceedings Part 3 Lnai 7198

Authors: Jeng-Shyang Pan ,Shyi-Ming Chen ,Ngoc-Thanh Nguyen

2012th Edition

3642284922, 978-3642284922

More Books

Students also viewed these Databases questions