Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code implementation to compute  |a-b| without using math.abs: 

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    double a = in.nextDouble();

    double b = in.nextDouble();

    double value = a - b;

    System.out.println("Enter a: ");

    a = in.nextDouble();

    System.out.println("Enter b: ");

    b = in.nextDouble();

    //If value is negative...make it a positive number.

    value = (value < 0) ? -value : value;

    System.out.println(a + "-" + b + "=" + (a - b));

    System.out.println(b + "-" + a + "=" + (b - a));

}

}

Can anyone tell me how to find the absolute value of the difference of two numbers without using math.abs? 

1 Answer

0 votes
by (19.7k points)

Below is the formatted code for it: 

import java.util.Scanner;

class A {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        double a;

        double b;

        System.out.println("Enter a: ");

        a = in.nextDouble();

        System.out.println("Enter b: ");

        b = in.nextDouble();

        double value = a - b;



 

        //If value is negative...make it a positive number.

        value = (value < 0) ? -value : value;

            System.out.println("|"+a + "-" + b +"|" + " =" + value);  // value should be printed here instead of (a-b) or (b-a)

        System.out.println("|"+b + "-" + a +"|" + " =" + value);

    }

}

Interested in Java? Check out this Java Certification by Intellipaat.   

Browse Categories

...