简体   繁体   中英

User input from main class in calculation Java

When I run it, it returns 0.0 which leads me to believe the calculation is not taking the user input.

I know I am missing something obvious but I've been looking at it too long.

Please help!

Input of x1 = -2, y1 = -3, x2 = -4, y2 = 4, should return 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
    }

}

This is my main class

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 should be defined and called as a method and return the calculated result as follows:

  1. In CalculateDistance class
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. In the main class:
System.out.println("The total distance between the two points is "
                            + position.calculateDistance());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM