我必须创建一个类来计算2个给定点之间的距离。教师给我们提供了所有必要的代码的上半部分,没有修改,即我正在创建类部件的问题。这是我迄今为止...计算2个给定点之间的距离
class Point{
int x;
int y;
public Point(){
this.x = 0;
this.y = 0;
}
public Point(int x, int y){
this.x = x;
this.y = y;
}
public double distance(int x, int y) {
double d = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));
return distance;
}
}
分配的上半部分看起来是这样的:
import java.util.Scanner;
class Assignment4{
public static void main(String[] args){
// first and second points
Point first, second;
// try parsing points from command line args
if(args.length==4){
// new Point(int x, int y) creates a new Point located at position (x,y)
first = new Point(Integer.valueOf(args[0]), Integer.valueOf(args[1]));
second = new Point(Integer.valueOf(args[2]), Integer.valueOf(args[3]));
}
// if not specified as argument, get points from user
else{
Scanner input = new Scanner(System.in);
System.out.println("Enter first point: ");
first = new Point(input.nextInt(),input.nextInt());
System.out.println("Enter second point: ");
second = new Point(input.nextInt(),input.nextInt());
}
//calculate distance
//double d = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));
double d = first.distance(second.x, second.y);
System.out.println("Distance between " +
"(" + first.x + "," + first.y + ")" +
" and " +
"(" + second.x + "," + second.y + ")" +
" is " + d);
System.out.println();
}
}
当我尝试和编译程序,它说:“找不到符号”,指到x2,x1,y2,y1和距离。
@ChthonicProject不是真的 - 'distance()'是一个实例方法,它试图计算当前'Point'和一个坐标由两个参数给定的点之间的距离。 – ajb 2014-11-21 06:53:06
作为作业的一部分,给定给你的是'距离'的定义,即“公共双距离(int x,int y)”,还是你的想法?我只是想知道为什么该方法必须使用'x'和'y'来代替另一个'Point'。 – ajb 2014-11-21 06:53:36