Search code examples
javaif-statementabsolute-value

Finding absolute value with if statement


I have 2 int variables which the user needs to enter, and I need to find the absolute value of their difference, is there a way to do it on the same principle I have started in this code?

    Scanner scn = new Scanner(System.in);

    int yourfloor, elefloor, desfloor;`enter code here`
    System.out.println("Please enter your current floor");
    yourfloor = scn.nextInt();
    System.out.println("Please enter the elevator current floor(before inviting)");
    elefloor = scn.nextInt();
    System.out.println("Please enter your destination floor");
    desfloor = scn.nextInt();

    int getTime = yourfloor - elefloor;
    if (getTime<0);
    {getTime*(-1)};

Solution

  • How about the ternary operator?

    //ASSIGNMENT   CONDITION             ? WHAT IF TRUE           : WHAT IF FALSE
    int getTime = (yourfloor > elefloor) ? (yourfloor - elefloor) : (elefloor-yourfloor);
    

    Or by changing your code to work:

    int getTime = yourfloor - elefloor;
    if (getTime<0) {
       getTime *= -1;
    }
    

    The ; at the end of your if completed the if statement - so the *(-1) was always executed. In addition, you need to use *= instead of *, because if you just multiply it, it will not do anything with the result, whereas *= is short for: getTime = getTime * -1, which will assign it back to getTime.

    Or of cause you could use Math.abs()...