2

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)};
Jan
  • 13,738
  • 3
  • 30
  • 55
Evy
  • 43
  • 7

2 Answers2

0

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()...

zpr
  • 2,886
  • 1
  • 18
  • 21
Jan
  • 13,738
  • 3
  • 30
  • 55
  • Seems like a very convoluted way to get the absolute value, the ternary statement isn't too readable (parenthesis would help), but to a newbie would probably shy them away from using it. Not a natural need for the ternary operator. I think `Math.abs()` should be preferred, since he is asking specifically about absolute value. – zpr Dec 20 '15 at 08:08
  • Right. But this has the feel of an "assignment" like question - so probably Math isn't allowed. See my edit of "making it right". – Jan Dec 20 '15 at 08:09
  • And... check out the implementation of Math.abs: `return (a < 0) ? -a : a;` ternary operator all over again... – Jan Dec 20 '15 at 08:16
-1

Try abs() which takes a number of any type as a parameter and returns the absolute value of it, in the same type.

abs(-3.1) == 3.1

So you could write:

int getTime = abs(yourfloor - elefloor);
zpr
  • 2,886
  • 1
  • 18
  • 21