java - Object can't access all the data from another object, but only what I've specified. How to fix? - TagMerge
2Object can't access all the data from another object, but only what I've specified. How to fix?Object can't access all the data from another object, but only what I've specified. How to fix?

Object can't access all the data from another object, but only what I've specified. How to fix?

Asked 1 years ago
1
2 answers

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()

Source: link

0

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.

Source: link

Recent Questions on java

    Programming Languages