Java: searching for elements by index of another element

I have a problem with the practice that I am trying to solve. I have three arrays accepted in a method. Names, age and salary. I have to return using string.format which shows salary, name and age

Arrays are the same length, and the corresponding elements in each array are connected. I have to find the smallest salary and use it to get the corresponding name and age of the person.

I can find the smallest salary, but I am confused about how to get the appropriate name and age, which is consistent with this.

Thank you in advance

Edit: if I found the lowest salary through this code, what is the capture function of this index and use this 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];
    }       
}
+4
4

- , , 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;
    }
}

. / , .

System.out.println(nameArray[index]);
System.out.println(ageArray[index]);

. , . Person , .

class Person{
   int age;
   String name;
   int salary;
}
+4
double smallSal = salaries[0];
int index = 0;

for(int i = 1; i < salaries.length; i++) {

    if(smallSal > salaries[i]) {
        smallSal = salaries[i];
        index = i;
    }       
}

, , .

.

, , ..

+2

, [], b [], c [] -

  • a [] .

"pos"

b [pos], c [pos]

  1. a [],

Change the values ​​of b [], c [] also when changing the values ​​of [] and access b [pos], c [pos]

+2
source

You can return the index of the payroll array and use the same index to get the name and age from other arrays.

public static int getSmallestSalaryIndex(double[] salaries) {

double smallSal = salaries[0];    
int index =0;
for(int i = 1; i < salaries.length; i++) {

    if(smallSal > salaries[i]) {
        smallSal = salaries[i];
        index =i;
    }       
}
   return index;
}

You must write the implementation according to the name of the method, do not include everything inside the same method. You do not need to pass the entire array (age, name) to getSmallestSalaryIndex.

int idx = getSmallestSalaryIndex(salaries);
System.out.printf("The person name %s is %d has salary %f", names[idx] ,ages[idx],salaries[idx]);
+2
source

Source: https://habr.com/ru/post/1692289/


All Articles