ArrayList x,y坐标距离计算

时间:2018-04-15 22:31:22

标签: java object arraylist

任何人都可以帮我弄清楚如何使这个计算有效吗?我一直在圈子里工作,老实说我不知道​​该怎么做。这是我正在处理的当前文件:

import java.util.*;
import java.io.*;

public class Assignment_12 {

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

      System.out.println("name goes here");
      System.out.println("You may quit at any time by typing \"Q\".");
      ArrayList<Double> numbers = new ArrayList<Double>();
      ArrayList<Double> numbers2 = new ArrayList<Double>();
      System.out.println("Please enter an X coordinate: ");
      //Point pnt = new Point();

      while (input.hasNextDouble()) {
         numbers.add(input.nextDouble());
         System.out.println("Please enter a Y coordinate: ");
         numbers2.add(input.nextDouble());

         double x = (double) numbers.get(0);
         double y = (double) numbers2.get(0);

         Point pnt = new Point(x, y);
         System.out.println(pnt.getX()); // just to make sure the "object created"?
         System.out.println(pnt.getY()); // same as before, I think
         System.out.println(pnt.distance(pnt.getX(), pnt.getY())); // how to calculate??
      }

      if (input.equals("Q")){
         System.exit(0);
      }
   }
}

这是我正在试图弄清楚如何使实际的实际计算工作的课程:

public class Point {

   private double x;
   private double y;

   public Point(){
      this.x = 0.0;
      this.y = 0.0;
   }

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

   public double distance(Point pt){
      return Math.sqrt((x - pt.x)*(x - pt.x) + (y - pt.y)*(y - pt.y));
   }

   public double getX(){
      return x;
   }

   public double getY(){
      return y;
   }
}

我真的在努力做什么。我似乎用pntx创建了y对象,但我不一定了解如何使计算的距离可用于打印。我试过System.out.println(pnt.distance(pnt.getX(), pnt.getY()));和其他类似的东西,但我只是难倒。任何建议将不胜感激!

1 个答案:

答案 0 :(得分:2)

仔细查看方法的签名:

double distance(Point pt)
//              ⬑ single parameter of type Point

此方法在Point上调用,您使用point.distance(...正确执行了该方法。但它需要一个参数,该参数的类型为Point。你没有通过Point。让我稍微改写你的代码:

double someX = pnt.getX();
double someY = pnt.getY();
pnt.distance(someX, someY)

这不起作用,因为您传递了两个double ,而不是一个Point 。那么可以做的是:

pnt.distance(pnt)
//           ⬑ single parameter of type Point

将此与您的行为进行比较:

pnt.distance(pnt.getX(), pnt.getY())
//           ⬑          ⬑ two parameters of type double

但是,我要指出,这将返回0,因为您刚刚计算了Point与自身的距离。尝试:

Point otherPnt = new Point(13, 8.5);
System.out.println(pnt.distance(otherPnt));

至少会返回一个更有趣的结果。

相关问题