Use the Power of Objects
Avoid using parallel arrays in Java. It brings unnecessary complexity, makes the code brittle and less maintainable.
Your code doesn't automatically become object-oriented just because of the fact that you're using an object-oriented language.
Objects provide you an easy way of structuring your data and organizing the code (if you need to implement some functionality related, to a particular data you know where it should go - its plane is in the class representing the data).
So, to begin with, I advise you to implement a class, let's call it CarSale
:
public static class CarSale {
private Month month;
private int amount;
// getters, constructor, etc
}
Or, if you don't need it to be mutable, it can be implemented as a Java 16 record
. In a nutshell, record
is a specialized form of class, instances of which are meant to be transparent carriers of data (you can not change their properties after instantiation).
One of the greatest things about records is their concise syntax. The line below is an equivalent of the fully fledged class with getters, constructor, equals/hashCode
and toString
(all these would be generated for you by the compiler):
public record CarSale(Month month, int amount) {}
java.time.Month
You've probably noticed that in the code above, property month
is not a String
. It's a standard enum Month
that resides in java.time
package.
When you have a property that might have a limited set of values, enum
is always preferred choice because contrary to a plain String, enum
guards you from making typo and also enums have an extensive language support. So you don't need this array filled with moth-names.
That's how your code might look like:
CarSale[] carSales = {
new CarSale(Month.JANUARY, 1234),
new CarSale(Month.FEBRUARY, 2343),
new CarSale(Month.MARCH, 1456),
// ...
};
// you might want to check if carSales is not is empty before accessing its first element
CarSale best = carSales[0];
for (CarSale sale: carSales) {
if (sale.getAmount() > best.getAmount()) best = sale;
}
JOptionPane.showMessageDialog(null,
"The highest car sales value is :" + best.getAmount() +
" which happened in the month of " + best.getMonth());
Note
Try to keep your code aligned with Java naming conventions. Only names of classes and interface should start with a capital letter.
In case if you've heard from someone that usage of parallel arrays can improve memory consumption, then I would advise to examine this question dipper and take a look at questions like this Why use parallel arrays in Java? In case of such tiny arrays the only thing are disadvantages of a fragile code.