Java 17 Recipes
-6. Working with Dynamic Arrays
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
7-6. Working with Dynamic Arrays
Problem You need a flexible data structure that can store a variable amount of data and allow for easy insertion and deletion of data. Solution Consider using an ArrayList class, which allows you to screen a list of stocks or a single stock based on a specific screen parameter (P/E, Yield, and Beta) and screen value. The class uses an ArrayList of the stocks in this list has a P/E (price-to-earnings ratio) of 15 or less.” Don’t worry if you’re not familiar with these stock market terms. Whatever you do, don’t use this class to make your stock investment decisions! public class StockScreener { enum Screen { PE, YIELD, BETA }; public static boolean screen(String stock, Screen screen, double threshold) { double screenVal = 0; boolean pass = false; Chapter 7 Data SourCeS anD ColleCtionS 269 switch (screen) { case PE: screenVal = Math.random() * 25; pass = screenVal <= threshold; break; case YIELD: screenVal = Math.random() * 10; pass = screenVal >= threshold; break; case BETA: screenVal = Math.random() * 2; pass = screenVal <= threshold; break; } System.out.println(stock + ": " + screen.toString() + " = " + screenVal); return pass; } /** * Parse through stock listing to determine if each stock passes the * screen tests. If a particular element does not pass the screen, then remove it. */ public static void screen(List threshold) { Iterator while (iter.hasNext()) { String stock = iter.next(); if (!screen(stock, screen, threshold)) { iter.remove(); } } } public static void main(String[] args) { List stocks.add("ORCL"); Chapter 7 Data SourCeS anD ColleCtionS 270 stocks.add("AAPL"); stocks.add("GOOG"); stocks.add("IBM"); stocks.add("MCD"); System.out.println("Screening stocks: " + stocks); if (stocks.contains("GOOG") && !screen("GOOG", Screen.BETA, 1.1)) { stocks.remove("GOOG"); } System.out.println("First screen: " + stocks); StockScreener.screen(stocks, Screen.YIELD, 3.5); System.out.println("Second screen: " + stocks); StockScreener.screen(stocks, Screen.PE, 22); System.out.println("Third screen: " + stocks); System.out.println("Buy List: " + stocks); } } The output from running this code varies because it randomly assigns a stock’s screen result value. Here is one sample of output from running the class. Screening stocks: [ORCL, AAPL, GOOG, IBM, MCD] GOOG: BETA = 1.9223516769748348 First screen: [ORCL, AAPL, IBM, MCD] ORCL: YIELD = 6.140018494585904 AAPL: YIELD = 7.875759429097191 IBM: YIELD = 7.715436753622726 MCD: YIELD = 2.419792753509281 Second screen: [ORCL, AAPL, IBM] ORCL: PE = 4.396013965331994 AAPL: PE = 14.200385457743778 IBM: PE = 7.6981860501796175 Third screen: [ORCL, AAPL, IBM] Buy List: [ORCL, AAPL, IBM] Chapter 7 Data SourCeS anD ColleCtionS |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling