gpt4 book ai didi

java - 其他类的方法和 toString() 的使用

转载 作者:行者123 更新时间:2023-11-30 01:42:44 25 4
gpt4 key购买 nike

我正在尝试使此代码正常工作,从 MAIN 上的用户接收 2 个点 (x, y) 和 (x1,y1) 并使用另一个类中的方法并进行计算。

另外,如果能收到有关 toString 的解释那就太好了。

import java.util.Scanner;
public class Test{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
double x , y , x1 , y1;
Pytaguras Triangle = new Pytaguras();

System.out.println("Hello , this program is using Pytagoras formula" +
" on the 4 point that you enter");
System.out.println("Please enter 4 points to calculate the distance");
x = scan.nextDouble();
y = scan.nextDouble();
x1 = scan.nextDouble();
y1 = scan.nextDouble();
Triangle.setDouble( x, y, x1, y1);
System.out.println("the distance between 2 points is :" + Triangle.calculate() );

}
}

public class Pytaguras
{
private double x, y, x1 ,y1 ;
public void setDouble(double _x, double _y, double _x1, double _y1)
{ _x=x;
_y=y;
_x1=x1;
_y1=y1;}

public double calculate(double _x , double _y , double _x1 , double _y1 )
{ double s;
s = Math.sqrt((_x-_y)*(_x-_y)+(_x1-_y1)*(_x1-_y1));
return s;
}

}

最佳答案

如果您想通过类Triangle的方法toString()接收距离计算,您只需实现它与方法计算相同:

使用toString的可能解决方案

你的类看起来像这样:

public class Pytaguras {
private double x, y, x1 ,y1 ;
public void setDouble(double _x, double _y, double _x1, double _y1) {
_x=x;
_y=y;
_x1=x1;
_y1=y1;
}

public static double calculate(double _x , double _y , double _x1 , double _y1 ) {
return Math.sqrt((_x-_y)*(_x-_y)+(_x1-_y1)*(_x1-_y1));
}

public String toString() {
return "Distance is " + Math.sqrt((x - y)*(x -y)+(x1 - y1)*(x1 - y1));
}
}

可能出了什么问题?

当您尝试像这样实现 toString() 时:

// code omitted for clarity

public double calculate(double _x , double _y , double _x1 , double _y1 ) {
double s; // variable declared locally, thus can be used only inside this method
s = Math.sqrt((_x-_y)*(_x-_y)+(_x1-_y1)*(_x1-_y1));
return s;
}

// code omitted for clarity

public String toString() {
return s; // will give compiler-error, since symbol/variable "s" is not visible here, but only inside method calculate
}

// code omitted for clarity

重构 = 优化代码

在实用程序方法上使用static:您的计算方法不依赖于任何变量(x,y,x1, y1) 在类内部声明,但仅在参数上声明。因此它是独立并且可以设为静态。因此,它会成为一个可以从外部调用的实用方法,例如Pytaguras.calculate(...)。请参阅Java Tutorial on static .

使用构造函数初始化变量:你的2点可以使用构造函数直接初始化。因此,您不需要同时调用 new Pytaguras()setDouble(x1, y1, x2, y2)。您可以简单地调用new Pytaguras(x1, y1, x2, y2)。请参阅Java Tutorial on constructor .

关于java - 其他类的方法和 toString() 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59380644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com