Reputation: 119
I'm just sort of messing around on Java trying to create a program that will display some basic info on stocks.. So far my code looks like this:
Stock class:
import java.util.Scanner;
public class Stock {
private String company_name;
private String ticker;
private String category;
private Double price;
public Stock()
{
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter company name: ");
this.company_name = scanner.nextLine();
System.out.print("Please enter stock TICKER: ");
this.ticker = scanner.nextLine();
System.out.print("Please enter the stock's category: ");
this.category = scanner.nextLine();
System.out.print("Please enter stock's current price: ");
this.price = scanner.nextDouble();
}
public Stock(String cn, String tic, String cat, Double p)
{
this.company_name = cn;
this.ticker = tic;
this.category = cat;
this.price = p;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
and my StockList class
import java.util.*;
public class StockList {
/* StockList's Array List */
private final ArrayList<Stock> stock_list = new ArrayList<Stock>();
/**
* Getter for StockList's Array List
* @return StockList's Array List
*/
public ArrayList<Stock> getStock_list() {
return stock_list;
}
/**
* Method to add stock
* @param stock is the stock you want to be added to array list
*/
public void add(Stock stock)
{
stock_list.add(stock);
}
/**
* Method to create a Stock object AND THEN add it to Array List
*/
public void add()
{
Stock stock = new Stock();
this.add(stock);
}
/**
* Have the user give a company name, find the matching name from the StockList Array List
* and then delete it, if it's there. Otherwise, return a friendly message telling the user
* that the stock was not found.
*/
public void delete()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the company name of the stock you wish to remove.");
String company_name = scanner.nextLine();
Iterator<Stock> iter = this.stock_list.iterator();
while(iter.hasNext())
{
if(iter.next().getCompany_name().equals(company_name))
{
System.out.println(company_name + " was successfully removed.");
iter.remove();
return;
}
}
System.out.println(company_name + " was not found in your list of current stocks.");
}
/**
* Simple print method for the StockList Array List
*/
public void print()
{
if(stock_list.isEmpty())
{
System.out.println("Your list is empty.");
return;
}
System.out.println("=========================================");
for (Stock value : stock_list) {
System.out.println("Company: " + value.getCompany_name());
System.out.println("Ticker: " + value.getTicker());
System.out.println("Category: " + value.getCategory());
System.out.println("Price: $" + value.getPrice());
}
System.out.println("=========================================");
}
public void sum_up_list() {
double total_investment_price = 0.0;
String most_invested_category;
Map<String, Integer> category_and_count = new HashMap<String, Integer>();
/* Get the categories and their percentages */
for (Stock value : stock_list) {
Integer j = category_and_count.get(value);
category_and_count.put(value.getCategory(), (j == null) ? 1 : j + 1);
total_investment_price += value.getPrice();
}
String max_cat = "NULL";
int max_cat_count = 0;
for (Map.Entry<String, Integer> val : category_and_count.entrySet()) {
if (category_and_count.get(val.getKey()) >= max_cat_count)
{
max_cat = val.getKey();
max_cat_count = val.getValue();
}
}
System.out.println("Total investments $" + total_investment_price);
System.out.println("The category I'm most invested in is " + max_cat +
" with " + max_cat_count + " stocks in this category.");
}
}
But right now I'm struggling with the sum_up_list() method. What I'm trying to do is create a HashMap containing the categories of each stock and the number of times that that particular category shows up each time on my stock_list. Right now it's keeping the category name but the count is off..
Essentially what I'm trying to do is go through the stock_list Array List and for each unique category add that to the hashmap, using the category as a String key for the hashmap. And then each subsequent time that the category/key is found to update the hashmap key's value by one. If this makes sense? I'm finding it hard to put into words right now..
Here's some output text I'm getting right now:
Please enter company name: Costco
Please enter stock TICKER: COST
Please enter the stock's category: Retail
Please enter stock's current price: 312.18
Please enter company name: Amazon
Please enter stock TICKER: AMZ
Please enter the stock's category: Tech
Please enter stock's current price: 3002.40
Please enter company name: AirBNB
Please enter stock TICKER: BNB
Please enter the stock's category: Tech
Please enter stock's current price: 142.50
Total investments $3457.08
The category I'm most invested in is Tech with 1 stocks in this category.
I would like the final output line to instead say:
The category I'm most invested in is Tech with **2** stocks in this category.
EDIT: I used njzk2's merge solution below and it worked just as I needed it too! Thanks for the help. Here's the updated sum_up_list() method which was the source of all my trouble:
public void sum_up_list() {
double total_investment_price = 0.0;
String most_invested_cat = "NULL";
int cat_count = 0;
Map<String, Integer> category_and_count = new HashMap<String, Integer>();
/* Get the categories and their percentages */
for (Stock value : stock_list) {
category_and_count.merge(value.getCategory(), 1, Integer::sum);
total_investment_price += value.getPrice();
}
for (Map.Entry<String, Integer> val : category_and_count.entrySet())
{
if(val.getValue() >= cat_count)
{
most_invested_cat = val.getKey();
cat_count = val.getValue();
}
}
System.out.println("Total investments $" + total_investment_price);
System.out.println("The category I'm most invested in is " + most_invested_cat +
" with " + cat_count + " stocks in this category.");
}
}
Upvotes: 0
Views: 131
Reputation: 160
Change below code
max_cat = val.getKey();
to
if(max_cat_count < val.getValue())
{
max_cat_count = val.getValue();
max_cat = val.getKey();
}
Upvotes: 1
Reputation: 39386
The main issue is getting the right count: category_and_count.get(value);
should be category_and_count.get(value.getCategory());
This is more easily done with the merge
method:
for (Stock value : stock_list) {
category_and_count.merge(value.getCategory(), 1, Integer::sum);
total_investment_price += value.getPrice();
}
Or even more simply with groupingBy
:
category_and_count = stock_list
.stream()
.groupingBy(Stock::getCategory, Collectors.counting());
total_investment_price = stock_list
.stream()
.collect(Collectors.summingInt(Stock::getPrice));
Upvotes: 1