我必須創建一個類來計算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