计算 Java 中主类的用户输入



当我运行它时,它返回0.0这让我相信计算没有接受用户输入。

我知道我错过了一些明显的东西,但我已经看了太久了。

请帮忙!

输入x1 = -2, y1 = -3, x2 = -4, y2 = 4,应返回7.28

public class CalculateDistance {
private double x1, y1; //position of first point
private double x2, y2; //position of second point
public double getx1() {
return x1;
}
public void setx1(double x1){
this.x1 = x1;
}
public double gety1() {
return this.y1;
}
public void sety1(double y1){
this.y1 = y1;
}
public double getx2() {
return x2;
}
public void setx2(double x2){
this.x2 = x2;
}
public double gety2() {
return this.y2;
}
public void sety2(double y2){
this.y2 = y2;
}
public double calculateDistance; {  //calculation of (x2-x1)squared + (y2-y1)squared
calculateDistance = Math.sqrt((((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)))); //formula which the square root of will be the distance
}
}

这是我的主要课程

import java.util.Scanner;
public class TestCalculateDistance {
public static void main(String[] args) { //method
CalculateDistance position = new CalculateDistance();
Scanner input = new Scanner(System.in);
System.out.println("To calculate the distance between two points, please enter the following values; " + 
"nFor the first point, What is the value of x? ");//asking user to enter the x position
position.setx1(input.nextDouble());
System.out.println("What is the value of y? ");
position.sety1(input.nextDouble());

System.out.println("For the second point, What is the value of x? ");
position.setx2(input.nextDouble());

System.out.println("What is the value of y? ");
position.sety2(input.nextDouble());
System.out.println("The total distance between the two points is "
+ position.calculateDistance);
}
}

calculateDistance应定义为方法并调用,并返回计算结果,如下所示:

  1. CalculateDistance课堂上
public double calculateDistance() {  //calculation of (x2-x1)squared + (y2-y1)squared
return Math.sqrt((((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)))); //formula which the square root of will be the distance
}
  1. 在主类中:
System.out.println("The total distance between the two points is "
+ position.calculateDistance());

相关内容

  • 没有找到相关文章

最新更新