user19471184
user19471184

Reputation:

Compare Values and return String

I have ltp and s1 , s2 and s3 values

(s1 , s2 , s3 denotes suppourt1 , suppourt2 , suppourt3 )

What I am trying to achieve is that ,

If the ltp is 2 points near S1 , display S1

If the ltp is 2 points near S2 , display S2

If the ltp is 2 points near S3 , display S3

I have tried using this

public class Test {

    public static void main(String[] args) {

        double ltp = 15.45;

        double s1 = 18.34;

        double s2 = 16.34;

        double s3 = 10.34;

        double s1Level = ltp - s1;

        double s2Level = ltp - s2;

        double s3Level = ltp - s3;
        
        

        if (s1Level <= 2) {
            System.out.println("S1");
        }

        else if (s2Level <= 2) {
            System.out.println("S2");

        }

        else if (s3Level <= 2) {
            System.out.println("S3");
        }

    }

}

Here ltp is 15.45 and its near s2 16.34 , I was expecting S2.

Upvotes: 0

Views: 41

Answers (1)

Nexevis
Nexevis

Reputation: 4667

You are subtracting a larger number from a smaller number, so you are getting a negative value for s1Level which of course will always be lower than 2. This means you will never reach the else if for s2Level since s1Level <= 2 is true.

If you want to compare the absolute values of the subtraction, simply use Math.abs(yourValue) which will always return the positive value of the number.

public static void main(String[] args) {
    double ltp = 15.45;

    double s1 = 18.34;
    double s2 = 16.34;
    double s3 = 10.34;

    double s1Level = Math.abs(ltp - s1);
    double s2Level = Math.abs(ltp - s2);
    double s3Level = Math.abs(ltp - s3);

    if (s1Level <= 2) {
        System.out.println("S1");
    }
    else if (s2Level <= 2) {
        System.out.println("S2");

    }
    else if (s3Level <= 2) {
        System.out.println("S3");
    }
}

Upvotes: 2

Related Questions