2014-11-21 4 views
-2

클래스에 2 개의 주어진 점 사이의 거리를 계산하는 클래스를 만들어야합니다. 강사는 필요한 부분을 수정하지 않고 필요한 모든 코드를 사용하여 과제의 상위 절반을주었습니다. 문제는 클래스 부분을 만드는 것입니다.주어진 2 점 사이의 거리 계산

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(); 
} 
} 

내가 시도하고 프로그램을 컴파일, 그것은 언급 "기호를 찾을 수 없습니다"라는 :이

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; 
} 
} 

과제의 상단 절반은 다음과 같습니다 ... 난 지금까지 무엇을 가지고 ~ x2, x1, y2, y1 및 거리. 여기

+0

@ChthonicProject 아니에요 -'distance()'는 인스턴스 메소드이고, 현재의'Point'와 두 개의 인자에 의해 좌표가 주어진 점 사이의 거리를 계산하려고합니다. – ajb

+0

과제의 일부로 주어진 '거리'의 정의, 즉 'public double distance (int x, int y)'입니까, 아니면 아이디어였습니까? 나는 왜 다른 방법 대신에'x'와'y'를 취해야하는지 궁금 할 것입니다. – ajb

답변

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 Y-2)); 이 라인

(2) 오류 2 스왑 :

복귀 D;

+0

감사합니다! 이것은 많은 도움이되었습니다. 하지만이 고정 부분을 사용하면 다음과 관련된 또 다른 오류가 발생합니다. 처음 = new Point (Integer.valueOf (args [0]), Integer.valueOf (args [1]))); second = new Point (Integer.valueOf (args [2]), Integer.valueOf (args [3])); } ill. 집에서 실행할 수있을 때 상세한 오류 정보를 얻으십시오 –

+0

확실한 문제 없음 :). 나는 고정 부분에 관해 당신이 말한 것을 이해하지 못합니다. 왜 유효 부분을 전달하면 코드의 해당 부분에 오류가 발생하는지 보지 못합니다. 오류 메시지를 보내 주시면 도와 드리겠습니다. – j4rey89