简体   繁体   English

为什么我不能使用 java.awt.geom.Point2D 中的距离方法?

[英]Why can't I use distance method from java.awt.geom.Point2D?

I can't use distance() from Point2D.我不能从 Point2D 使用distance() Please help me fix my code, thank you!请帮我修复我的代码,谢谢!

import java.util.Scanner;

import java.awt.geom.Point2D.Double;

public class TestPoint2D {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter point 1");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();
        
        System.out.print("Enter point 2");
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();
        
        Point2D p1 = new Point2D(x1, y1);
        Point2D p2 = new Point2D(x2, y2);
        System.out.println(p1.distance(p2));
    }
}

As Point2D docs say:正如Point2D 文档所说:

This class is only the abstract superclass for all objects that store a 2D coordinate.这个类只是存储二维坐标的所有对象的抽象超类。 The actual storage representation of the coordinates is left to the subclass.坐标的实际存储表示留给子类。

So you need to use Point2D.Double or Point2D.Float to initialize the object.所以需要使用Point2D.DoublePoint2D.Float来初始化对象。

So this code to initialize Point2D works:所以这个初始化Point2D代码有效:

Point2D p1 = new Point2D.Double(x1, y1);
Point2D p2 = new Point2D.Double(x2, y2);

This "problem" is because Point2D is an abtract class.这个“问题”是因为Point2D是一个抽象类。 You can check here how works if you have doubts.如果您有疑问,可以在此处查看工作原理。 But, to associate it with the "Point2D problem", check the first paragraphs and you will understand better.但是,要将其与“Point2D 问题”联系起来,请检查第一段,您会更好地理解。

Abstract class : is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).抽象类:是一个受限制的类,不能用于创建对象(要访问它,它必须从另一个类继承)。

That's exactly the problem (cannot create objects) and the solution (inherit from another class)这正是问题(无法创建对象)和解决方案(从另一个类继承)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM