I have a practice problem I am trying to solve. I have three arrays accepted into a method. Names, ages, and salaries. I am to return using string.format that shows the salary, name, and the age
The arrays are the same length and the corresponding elements in each array are related. I am supposed to find the smallest salary and use that to get the corresponding name and age of the person.
I am able to find the smallest salary, but I am confused on how to get the corresponding name and age that goes along with that.
Thank you in advance
Edit: If I found the smallest salary through this code, what is the function to grab this index and use that index to get the corresponding elements:
public static String getSmallestSalaryString(String[] names, int[] ages, double[] salaries ) {
double smallSal = Integer.MAX_VALUE;
for(int i = 0; i < salaries.length; i++) {
if(smallSal > salaries[i]) {
smallSal = salaries[i];
}
}
You somehow knew the smallest salary lets say it is smallestSalary
.
// Find the index corresponding to the smallest salary
int index = -1;
for(int i=0; i<salaryArray.length; i++){
if(salaryArray[i] == smallestSalary){
index = i;
}
}
Now you have the index. so just return/use names, ages.
System.out.println(nameArray[index]);
System.out.println(ageArray[index]);
But having data like can cause data inconsistency. You can have a class to group each person related info. Person class can be as simple as this.
class Person{
int age;
String name;
int salary;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With