我正在制作一个用于练习的距离公式计算器,但是当我实例化变量时,我无法让程序在控制台上运行。我在这里做错了什么?也欢迎任何有关缩短代码或提高代码效率的反馈。我把它附在这里:
DistFormula.java
public class DistFormula {
public DistFormula() {
}
// Variables
private double x1, x2, y1, y2, diff1, diff2, part1, part2, ans;
// Get first X
public double X1(double x1) {
return x1;
}
// Get first Y
public double Y1(double y1) {
return y1;
}
// Get second X
public double X2(double x2) {
return x2;
}
// Get second Y
public double Y2(double y2) {
return y2;
}
// Set first difference
public double setFirstPart() {
diff1 = x2 - x1;
part1 = Math.pow(diff1, 2);
return part1;
}
// Get first difference
public double getFirstPart() {
return part1;
}
// Set second difference
public double setSecondPart() {
diff2 = y2 - y1;
part2 = Math.pow(diff2, 2);
return part2;
}
// Get second difference
public double getSecondPart() {
return part2;
}
// Set answer
public double setFinalAns() {
ans = Math.sqrt(part1 + part2);
return ans;
}
// Get answer
public double getFinalAns() {
return ans;
}
public String toString() {
return "Distance between coordinates: " + ans;
}
}
主.java
public class Main {
public static void main(String[] arguments) {
DistFormula newFormula = new DistFormula();
newFormula.X1(10.1);
newFormula.Y1(18.2);
newFormula.X2(12.9);
newFormula.Y2(17.5);
newFormula.setFirstPart();
newFormula.setSecondPart();
newFormula.setFinalAns();
newFormula.toString();
}
}
最佳答案
首先,我认为您需要某种方式来输入每个变量的值。
public void setX1(double x1) {
this.x1=x1;
}
此外,如果您希望它更短,您可以通过构造函数传递这些值。
public DistFormula(double x1, double x2, double y1, double y2) {
this.x1=x1;
this.x2=x2;
this.y1=y1;
this.y2=y2;
}
你当然可以把它分解成小部分,但你也可以只有一种方法来计算确切的答案。
public double calculate() {
return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
}
如果您使用我提到的第一种方式,则需要执行(在 Main 中):
DistFormula newFormula = new DistFormula();
newFormula.setX1(10.1);
newFormula.setY1(18.2);
newFormula.setX2(12.9);
newFormula.setY2(17.5);
double answer=newFormula.calculate();
System.out.println("Distance between coordinates: " + answer);
如果使用第二种方式:
DistFormula newFormula = new DistFormula(10.1,18.2,12.9,17.5);
double answer=newFormula.calculate();
System.out.println("Distance between coordinates: " + answer);
关于Java – 运行距离公式程序的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32015415/