Before anything, I would like to say that I am entirely new to Java, I only started understanding the very basics of it a few days ago.
I have a problem with objects here and I will show you what I mean.
This is the code for one of the functions, which is supposed to show me the stock item that has the most frequency:
InternalComponent ic = new InternalComponent("Intel", 4, 35.0, 3200.00);
public void FindMostFrequency()
{
double temp = 0;
for (int i = 0; i< Stock.size(); i )
if (ic.frequency > temp)
temp = ic.frequency;
System.out.println("The stock with most frequency is: " temp );
}
The problem is that it uses the information only from a specific object and I would like to make it so it uses it from all objects.
Once again, I would like to point out that, what I've done here, is most likely wrong. Please point out any mistakes if possible, I really appreciate any help I can get.
This is the code for the InternalComponent class:
package com.company;
public class InternalComponent extends Stock {
protected double frequency;
public InternalComponent(String manufacturer, int count, double price,double frequency) {
super(manufacturer, count, price);
this.frequency = frequency;
}
@Override
public String toString() {
return "InternalComponent{"
"frequency=" frequency
'}';
}
}
CodePudding user response:
I'd use something like this ... you need a 2nd variable to capture the Stock, and a method to get the Stocks (getStocks()):
public void FindMostFrequency()
{
double temp = 0;
Stock mostFrequentStock = null;
for (Stock aStock : getStocks()) {
var frequency = aStock.frequency
if (temp < frequency) {
temp = frequency;
mostFrequentStock = aStock
}
}
System.out.println("The stock with most frequency is: " mostFrequentStock);
}
It would also be better to access the variable using a getter instead of directly, ie getFrequency()
CodePudding user response:
Your code looks almost correct but it doesn't seem like you define the body of the for loop with curly braces. As other posters have mentioned using a foreach loop is usually preferred in cases like this.
Looping through each of the elements and simply invoking a getFrequency() method would be better. Then compare that with your current maxFrequency value. It's usually good practice to make the instance variables of a class private and have them only accessible through getters and setters.
