Vilmantė Buožytė
Vilmantė Buožytė

Reputation: 9

How to find the nearest value from array?

public class A6{
    public static void main(String[] args){
        String personInfo[][]={ 
                {"Anderson",  "Varejao",     "1125"},
                {"Giorgi",  "Tevzadze",      "1125"},
                {"Will",      "Cherry",      "1225"},
                {"Kevin",     "Love",        "2525"},
                {"Kyrie",     "Livings",      "454"},
                {"Dion",      "Malborg",    "6250" } 
        };

        //max - who has the highest salary
        if(args[0].equals("max")){
            int max = Integer.parseInt(personInfo[0][2]);

            for(int i = 0; i < personInfo.length; i++) {
                int l = Integer.parseInt(personInfo[i][2]);        
                if(max < l){
                    max = l;
                }
             }

            for(int i = 0; i < personInfo.length; i++) {
                if(max == Integer.parseInt(personInfo[i][2])){
                     System.out.println(personInfo[i][0]);
                }
            }
            System.out.println("His sallary is:" +max );


        //  va ZZZ        - who has the closest salary to value ZZ
        if(args[0].equals("va")){
            for(int iž0; i < personInfo.length; i++{

            int l = Integer.parseInt(personInfo[i][2]);
            ...

        }
    }
}

I already wrote a method that finds person with a highest salary and now I am trying to found who has the closest salary to my entered value. For example: I enter into command line java A6 456 and should get answer from a command line Kyrie Livings. I have started doing this by writing a for loop and converting String values to int from personInfo. Any advices?

Upvotes: 0

Views: 64

Answers (1)

CodeHunter
CodeHunter

Reputation: 2082

Try this: (considering there are no constraints on memory usage):

int index = 0, minDiff = 0, diff = 0;

for(int i = 0;i<personInfo.length;i++){
    diff = Math.abs(personInfo[i][2] - inputVal);
    if(diff<minDiff){
        minDiff = diff;
        index = i;
    }        

}
return personInfo[index][2];

inputVal is the parameter you will pass to this function for which you want to find the nearest salary. You can modify this logic to accommodate your needs for this use case.

Upvotes: 1

Related Questions