I want to store made up stock information in an ArrayList. The stock information being stored is the stock symbol, number of shares, and the price of each share. If the user inputs 1, they are prompted to enter new stock information. If they enter 2, they can search for a stock symbol and if it is in the ArrayList, it will print the LIFO average cost of the last 250 shares entered into the ArrayList (sum of the cost of the last 250 shares / 250).
What I have so far just stores the information entered into an ArrayList. I have a few questions:
- How can I have the user input multiple data types into one element of an ArrayList? Storing the input as sym, amt, and cost and then having
ArrayList<stock> StockList = new ArrayList<stock>();
StockList.add(stock(sym,amt,cost));
doesn't work and I don't know why.
- Once the user inputs the information into the ArrayList, I want to prompt the user to input a stock symbol and it will display the average of the last 250 shares entered. How do you search an ArrayList and then print the average of the last 250 shares entered even if they were entered for example as: AAPL 125 536.86 and GOOG 300 1120.15
This is what I have so far:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class stock {
String name;
int shares;
double price;
public void Stock(String name, int shares, double price){
this.name = name;
this.shares = shares;
this.price = price;
}
public String getSym(){
return name;
}
public int getShares(){
return shares;
}
public double getPrice(){
return price;
}
public void setSym(){
this.name = name;
}
public void setShares(){
this.shares = shares;
}
public void setPrice(){
this.price = price;
}
public void add(String name, int shares, double price){
}
public static void main(String[] args) {
int choice = 0;
ArrayList<Stocks> stock = new ArrayList<Stocks>();
while (choice == 0){
System.out.println("Enter 1 to input a new stock, or 2 to query a stock's price, 3 to quit: ");
Scanner sc1 = new Scanner (System.in);
choice = sc1.nextInt();
if (choice == 1){
System.out.println("Please enter the stock symbol: ");
String sym = sc1.next();
System.out.println("Please enter the number of shares: ");
int amt = sc1.nextInt();
System.out.println("Please enter the price per share: ");
double cost = sc1.nextDouble();
for(int i = 0; i < amt; i++){
ArrayList<stock> StockList = new ArrayList<stock>();
StockList.add(stock(sym,amt,cost));
}
choice = 0;
for (int i = 0; i < StockList.size(); i++) {
System.out.println(myArray[i])
}
if (choice == 3){
System.exit(0);
}
}
}}