0

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.

3
  • What output did you expect? Why did you expect it? What output did you get instead? Commented Nov 9, 2022 at 13:50
  • 1
    You are not thinking of cases where the difference might be a negative number. Either use some method to turn your calculated subtractions s1Level etc. into absolut values, or change your if conditions to if (s1Level >= -2 && s1Level <= 2) Commented Nov 9, 2022 at 13:56
  • Also, using else if won't help if all the deltas are within the range. Which one do you want? The smallest? Largest? All of them? Commented Nov 9, 2022 at 14:01

1 Answer 1

2

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");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.