扩展Java Point类以查找中点 [英] Extending java point class to find midpoint

查看:171
本文介绍了扩展Java Point类以查找中点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为即将参加的考试而学习,并且正在研究示例问题,尤其是以下问题:

Im studying for an upcoming exam and am working at sample problems, in particular the following one:

添加到Point类的实例方法下面,该方法称为Midpoint,该方法返回Point类型的对象,该对象表示两个点的中点,其中一个点作为参数提供,另一个点作为当前点(即,由本地实例变量).请注意,中点将返回一个新的Point对象.充分利用Point类,编写一个读取两个点并打印它们的中点的程序.输入由两行组成,其中每行包含一个点的x和y坐标.下面是输入/输出的示例,输入以粗体显示:

Add to class Point below an instance method called midpoint which returns an object of type Point representing the midpoint of two points, where one of the points is supplied as a parameter and the other is the current point (i.e. the point provided by the local instance variables). Note that midpoint returns a new Point object. Making good use of class Point, write a program which reads two points and prints their midpoint. The input consists of two lines where each line contains the x- and y-coordinates of a point. An example of input/output follows, with input indicated by bolding:

Enter two points
2.1 3.2
3.0 2.8
The midpoint is (2.55,3.0)

我的point类代码如下,并且看起来还不错(可以指出任何错误或改进之处):

My code for the point class is as follows and seems to be ok (feel free to point out any errors or improvements):

 class Point {


private double x, y; // coordinates


Point(double x0, double y0){ // all-args constructor

    x = x0; y = y0;

}



Point(){}; // no-args constructor (defaults apply)



void get() { 

    x = Console.readDouble(); 

    y = Console.readDouble();

}

public Point midPoint(Point p) {
     double mx = (p.x + x)/2;
     double my = (p.y + y)/2;
     return new Point(mx,my);
}


public String toString() 
{ 

    return "(" + x + "," + y + ")";
}

}

我遇到麻烦的地方实际上是在下面的代码中使用我的midPoint方法,任何建议都是值得的.

And where I run into trouble is in actually using my midPoint method in the below code, any advice is appreciated.

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

class Midpoint extends Point
{
public static void main (String[] args ) {

    Scanner scanner = new Scanner(System.in);

    System.out.println("Please enter two points:");
    double x1 = scanner.nextDouble();
    double y1 = scanner.nextDouble();
    double x2 = scanner.nextDouble();
    double y2 = scanner.nextDouble();

    Point p1 = new Point(x1, y1);
    Point p2 = new Point(x2, y2);



    p1.get();
    return midPoint(p2);
}
}

推荐答案

get()方法的调用似乎是不必要的.

The call to get() method seems unnecessary.

其次,使用一个对象(根据问题的要求)调用您的midPoint.因此,应该是:

Secondly, call your midPoint using an object(as per the requirement in the question). Hence, it should be:

p1.midPoint(p2);

最后,由于该方法返回Point类型,因此请确保您捕获返回的内容.

Finally, since that method returns a Point type, ensure you catch what is returned.

Point p3 = p1.midPoint(p2);

这篇关于扩展Java Point类以查找中点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆