toString方法未调用。JAVA
我编写以下程序来调用toString方法未调用。JAVA,java,methods,invoke,tostring,Java,Methods,Invoke,Tostring,我编写以下程序来调用toString方法,但它不起作用 import java.util.Scanner; public class findarea_class { public static void main(String[] args) { findarea_class objtostring = new findarea_class(1.0,1.0); objtostring.setelements(); } doub
toString
方法,但它不起作用
import java.util.Scanner;
public class findarea_class {
public static void main(String[] args)
{
findarea_class objtostring = new findarea_class(1.0,1.0);
objtostring.setelements();
}
double width;
double height;
Scanner input = new Scanner(System.in);
findarea_class()
{
}
findarea_class(double width,double height)
{
this.width = width;
this.height = height;
}
public String toString()
{
return "width is: "+this.width+" and height is: "+this.height+"\n"
+"The area is : "+getarea(width,height)+"\n"
+"The perimeter is: "+getperimeter(width,height);
}
double getarea(double width,double length)
{
double area = width * length;
return area;
}
double getperimeter(double width,double length)
{
double perimeter = (2 * length) + (2 * width);
return perimeter;
}
double getwidth()
{
System.out.println("Please the width for calculation:");
double inputwidth = input.nextDouble();
System.out.println("Width is:"+inputwidth);
return inputwidth;
}
double getheight()
{
System.out.println("Please enter the height for calculation:");
double inputheight = input.nextDouble();
System.out.println("Height is:"+inputheight);
return inputheight;
}
void setelements()
{
double newwidth;
double newheight;
newwidth = getwidth();
newheight = getheight();
System.out.println("The new area is : "+getarea(newwidth,newheight));
System.out.println("The new perimeter is `enter code here`: "+getperimeter(newwidth,newheight));
}
}
您没有调用toString()。将它传递给任何可以显示它的对象。使用:
System.out.println(objtostring.toString());
您正在尝试重写
对象
类的toString
方法。试试这个
@Override
public String toString() {
return "width is: "+this.width+" and height is: "+this.height+"\n"
+"The area is : "+getarea(width,height)+"\n"
+"The perimeter is: "+getperimeter(width,height);
}
并将其命名为
objectName.toString()代码>。在本例中,请使用类似的内容。objtostring.toString()代码>您的主方法应该打印对象,或者您可以将println调用放入构造函数中(尽管我不太喜欢)
我的意思是它没有调用toString()方法。该部分的其余部分工作正常,但我想调用toString()方法来显示defaule值width=1.0,height=1.0。我在代码中甚至看不到一个大写字母(将强制使用的字母分开)。请遵循Java命名约定。您希望在哪里调用toString()
?谢谢。它正在工作。:)它现在正在工作。缺少的是,我正在传递参数,但没有缺少显示方法。我从“Whoppa”那里得到了帮助,它现在正在工作。:)很高兴我能帮忙!如果我的答案是“最佳”,那么选择我的帖子附近的绿色复选标记,这将标记为你的“最佳答案”。
public static void main(String[] args)
{
findarea_class objtostring = new findarea_class(1.0,1.0);
System.out.println(objtostring);
objtostring.setelements();
}