2014-11-21 159 views
-2

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

+0

@ChthonicProject不是真的 - 'distance()'是一個實例方法,它試圖計算當前'Point'和一個座標由兩個參數給定的點之間的距離。 – ajb 2014-11-21 06:53:06

+0

作爲作業的一部分,給定給你的是'距離'的定義,即「公共雙距離(int x,int y)」,還是你的想法?我只是想知道爲什麼該方法必須使用'x'和'y'來代替另一個'Point'。 – ajb 2014-11-21 06:53:36

回答

0

這裏:

class Point{ 
    int x; 
    int y; 

    ..... 
    ..... 

    public double distance(int x, int y) { 
     double d = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2)); //ERROR IN THIS LINE 
     return distance; //ERROR HERE TOO...(2) 
    } 
} 

沒有X1,X2,Y1,在類或方法參數定義Y2。

使用以下行交換它:

雙d = Math.sqrt(Math.pow(this.x-X,2)+ Math.pow(this.y-γ,2));

(2) 錯誤2交換與該行:

返回d;

+0

謝謝!這幫助了很多。但是當我使用該固定部分,我得到另一個錯誤有關: 第一=新點(Integer.valueOf(參數[0]),Integer.valueOf(參數[1])); second = new Point(Integer.valueOf(args [2]),Integer.valueOf(args [3])); } 生病得到詳細的錯誤信息時,即時通訊能夠在家裏 – 2014-11-21 21:25:11

+0

肯定沒問題:)運行它。我不明白你對固定部分所說的話,如果你傳遞了有效的參數,我不明白爲什麼那部分代碼會給出錯誤。給我發送錯誤信息,然後我可以幫助你。 – j4rey89 2014-11-22 14:03:08