我编写以下程序来调用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));
}
}
答案 0 :(得分:1)
你没有调用toString()。将它传递给任何可以显示它的东西。使用:
System.out.println(objtostring.toString());
答案 1 :(得分:1)
你的主要方法应该打印对象,或者你可以把println调用放在你的构造函数中(虽然我不是那个人的忠实粉丝)。
public static void main(String[] args)
{
findarea_class objtostring = new findarea_class(1.0,1.0);
System.out.println(objtostring);
objtostring.setelements();
}
答案 2 :(得分:0)
您正试图覆盖toString
类的Object
方法。试试这个。
@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();