如何正确修复我的函数调用(java)?

时间:2014-02-21 02:54:02

标签: java

这只是代码的一小部分,因为我觉得这足以让我的观点得以实现。

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());

每当我尝试运行它时,它只会将行的长度设为0.0。 起初我试图传递line1作为参数,但后来我意识到我不能(或至少不知道如何)调用它,因为我不能做Line.length(line1)或line1.length( LINE1)。

1 个答案:

答案 0 :(得分:2)

你说:

  

我尝试过一个简单的1,1和2,2。预期产量为1.41,我得到的是0.0

您在方法中混淆了参数的顺序。您的方法列出了x1,x2,y1,y2,并且使用它,1,1,2,2将检查从点1,2到1,2的行长度,即0.0。我认为您要将参数顺序更改为x1,y1,x2,y2。

实际上,您应该澄清您的参数变量以使其自我评论。摆脱a,b,c,d并改为: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;
  }