Java Arithmetic Operator calculate distance of two points

Question

We would like to calculate distance of two points.

Prompt the user to enter two points (x1, y1) and (x2, y2).

Display their distance between them.

import java.util.Scanner;

public class Main {

  public static void main(String[] String) {

    Scanner input = new Scanner(System.in);

    System.out.print("Enter x1 and y1: ");
    double x1 = input.nextDouble();
    double y1 = input.nextDouble();

    System.out.print("Enter x2 and y2: ");
    double x2 = input.nextDouble();
    double y2 = input.nextDouble();

    //your code here

    System.out.println("The distance between the two points is " + distance);

  }/*from   w w w .ja  va 2s  .  com*/
}


import java.util.Scanner;

public class Main {

  public static void main(String[] String) {

    Scanner input = new Scanner(System.in);

    System.out.print("Enter x1 and y1: ");
    double x1 = input.nextDouble();
    double y1 = input.nextDouble();

    System.out.print("Enter x2 and y2: ");
    double x2 = input.nextDouble();
    double y2 = input.nextDouble();

    double a = (Math.pow((x2 - x1), 2)) + (Math.pow((y2 - y1), 2));
    double distance = Math.pow(a, 0.5);

    System.out.println("The distance between the two points is " + distance);

  }
}

Note

To define a method to do the calculation:

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter x1 and y1: ");
    double x1 = input.nextDouble();
    double y1 = input.nextDouble();
    System.out.print("Enter x2 and y2: ");
    double x2 = input.nextDouble();
    double y2 = input.nextDouble();

    double distance = distance(x1, y1, x2, y2);

    System.out.println("The distance between the two points is " + distance);
  }/* w  w w .ja v a  2s. co  m*/

  private static double distance(double x1, double y1, double x2, double y2) {
    return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
  }
}



PreviousNext

Related