我正在为即将参加的考试而学习,并且正在研究示例问题,尤其是以下问题:
添加到类Point中,下面是一个称为midpoint的实例方法,该方法返回Point类型的对象,该对象表示两个点的中点,其中一个点作为参数提供,另一个是当前点(即由点提供的点)。本地实例变量)。请注意,中点将返回一个新的Point对象。充分利用Point类,编写一个读取两个点并打印其中点的程序。输入由两行组成,其中每行包含一个点的x和y坐标。下面是输入/输出的示例,输入以粗体显示:
Enter two points
2.1 3.2
3.0 2.8
The midpoint is (2.55,3.0)
我的point类代码如下,并且似乎还可以(请指出任何错误或改进):
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方法,任何建议都值得赞赏。
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()
方法的调用似乎是不必要的。第二,使用对象调用您的midPoint
(根据问题的要求)。因此,应为:
p1.midPoint(p2);
最后,由于该方法返回Point
类型,请确保您已捕获返回的内容。
Point p3 = p1.midPoint(p2);
Point p1 = new Point(whatever);
Point p2 = new Point(whatever);
Point p3 = p1.midPoint(p2);
p1.midPoint(p2)
,因此不需要扩展点类p1.get()
实际在做什么?碰巧与扫描仪一样吗?MidPoint
类不应扩展Point
类。我认为您这样做是为了使用midPoint方法,但这是错误的。您没有向Point类添加任何新行为。 public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
int d=sc.nextInt();
System.out.println((a+c)/2,(b+d)/2);
}
}