计算Java中主类的用户输入

问题描述 投票:0回答:1

当我运行它时,它返回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);

    }
}
java user-input
1个回答
4
投票

[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());
© www.soinside.com 2019 - 2024. All rights reserved.