用if语句查找绝对值

时间:2015-12-20 07:54:58

标签: java if-statement absolute-value

我有两个用户需要输入的int变量,我需要找到它们差异的绝对值,有没有办法按照我在这段代码中开始的相同原理来做呢?

    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)};

2 个答案:

答案 0 :(得分:0)

三元运算符怎么样?

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

或者将代码更改为:

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

;末尾的if完成了if语句,因此*(-1) 总是执行。此外,您需要使用*=而不是*,因为如果您只是将其相乘,则不会对结果执行任何操作,而*=则适用于:getTime = getTime * -1 },将其分配回getTime

或者您可以使用Math.abs() ...

答案 1 :(得分:-1)

尝试使用任意类型的abs()作为参数,并以相同的类型返回它的绝对值。

abs(-3.1) == 3.1

所以你可以写:

int getTime = abs(yourfloor - elefloor);