Question

I am new to programming and looking for help into finding the distance between points

What I currently have is this:

import java.util.*;

class WS8Q2 {
public static void main(String[] args){
    Scanner in = new Scanner (System.in);

    double x0=0;
    double x1=0;
    double y0=0;
    double y1=0;

    System.out.println("Please enter 4 numbers");
    x0=in.nextDouble();

    double distance = (x0, y1, x1, y0);
    System.out.print(answer);
    }


    public static double distance (x0, y1, x1,y0) {
        return Math.Sqrt ((x1 - y0) * (y1-y0) + (x1-x0) * (x1-x0));
    }

I am really unsure of how to do it, as I have never done distances before, and I am just completely lost, have tried to look up certain formulas but the only thing I found that seemed as some what useful to me is in this website link Which doesn't seem to say much to me

EDIT: Here is the question and what I am trying to achieve by the way:

Design a function distance that takes four fractional number parameters x0, y0, x1, and y1, and returns the distance between points (x0, y0) and (x1, y1). (Look up the formula if you can’t remember it!)

Was it helpful?

Solution 2

First, you want to print distance not answer. Second, it gave you the answer on your link.... try this

public static double distance (double x0, double y1, double x1, double y0) {
  return Math.hypot(x1-x0, y1-y0); // <-- From your link.
}

The formula for finding the distance between two points is precisely the same as the Pythagorean Theorem, find the length of the hypotenuse. That is c2 = a2 + b2.

Finally, you need to read in all four doublle(s)... not just one.

x0=in.nextDouble(); // Good.            1
x1=in.nextDouble(); // And another...   2
y0=in.nextDouble(); // And another...   3
y1=in.nextDouble(); // One more.        4

OTHER TIPS

The distance equation for two point(x0, y0) and (x1, y1) should be:

Math.Sqrt ((x1 - x0) * (x1-x0) + (y1-y0) * (y1-Y0));

consider approaching as OOP: declare a class Point with (x ,Y) attribute, declare a setLocation(a, b) function and declare getDistance(Point) function:

class Point
{
   double x;
   double y;

   Point(double x, double y)
   {
      this.x = x;
      this.y = y;
  }

  public double getDistance(Point p)
  {
    // now implement it
  } 
}

In Addition, if you are not already aware of java has a Point2D class which has a distance(double px, double py) function.

You could calculate the distance using this function...

public static double distance (x0, y1, x1,y0) {
    return Math.Sqrt (Math.pow((y1 - y0),2) + Math.pow((x1-x0),2));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top