我必须创建一个类来计算类的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和distance。
答案 0 :(得分: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。
使用以下行交换它:
double d = Math.sqrt(Math.pow(this.x-x,2)+ Math.pow(this.y-y,2));
(2) 错误2与此行交换:
返回d;