简体   繁体   中英

How do I properly fix my function calling (java)?

This is just a small portion of the code, since I feel like it would be enough to get my point across.

public class Line { 

    private double x1; 
    private double x2; 
    private double y1; 
    private double y2; 

    public Project2(double a,double b,double c,double d) { 
        x1 = a;
        x2 = b;
        y1 = c;
        y2 = d;
    }

    public double length () { //the length of a line
        double step1 = Math.pow((x1-x2),2);
        double step2 = Math.pow((y1-y2),2);
        double step3 = step1+step2;
        double step4 = Math.sqrt(step3);
        return step4;}}


import java.util.Scanner;

public class Project2Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);



        System.out.println("Enter starting coordinates for a line (starting with x then y): ");
        double a = input.nextInt();
        double b = input.nextInt();
        System.out.println("Enter ending coordinates for the line (starting with x then y): ");
        double c = input.nextInt();
        double d = input.nextInt();
        Line line1 = new Line(a,b,c,d);


        System.out.println("The length of the line is: " + line1.length());

Whenever I try to run it, it just gives length of the line as 0.0. At first I tried to pass line1 as an argument, but then I realized that I couldn't (or at least didn't know how to) call it since I couldn't do Line.length(line1) or line1.length(line1).

You state:

I tried with just a simple 1,1 and 2,2. Expected output was 1.41, what I got was 0.0

You're confusing the order of parameters in your method. Your method lists x1, x2, y1, y2, and with this, 1, 1, 2, 2, will check the length of line from point 1, 2 to 1, 2 which is 0.0. I think that you want to change your parameter order to x1, y1, x2, y2.

In fact, you should clarify your parameter variables to make them self commenting. Get rid of a, b, c, d and change to: x1, y1, x2, y2:

public class Line { 

  // order changed
  private double x1; 
  private double y1; 
  private double x2; 
  private double y2; 

  // parameter names clarified and order changed
  public Project2(double x1, double y1, double x2, double y2) { 
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
  }

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