Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Element finding through the index of another element

Tags:

java

arrays

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];
    }       
}
like image 725
Cowboy coder Avatar asked Dec 23 '22 11:12

Cowboy coder


1 Answers

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;
}
like image 160
Ran8 Avatar answered Feb 23 '23 15:02

Ran8