2014-02-16 127 views
-1

我写下面的程序来调用toString方法,但它不起作用。toString方法未调用。 java

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

我的意思是它不调用toString()方法。其余部分工作正常,但我想调用toString()方法来显示defaule值width = 1.0和height = 1.0。 – user1528581

+3

我甚至在代码中看不到一个* UpperCase *字母(把你被迫去的那些字母分开)。请遵循Java命名约定。 –

+4

你期望在什么地方调用'toString()'? – Pshemo

回答

1

你没有调用toString()。将它传递给任何可以显示它的东西。用途:

System.out.println(objtostring.toString()); 
+0

谢谢Whoppa。它正在工作。 :) – user1528581

+0

它现在正在工作。缺少的是,我传递参数,但没有显示方法丢失。我得到了“Whoppa”的帮助,现在正在工作。 :) :) – user1528581

+0

很高兴我能帮忙!如果我的答案是“最好的”,那么选择我的帖子附近的绿色复选标记,将其标记为您的“最佳答案”。 – Whoppa

0

您试图重写Object类的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();

1

你的主要方法应该打印对象,或者你可以把println调用放入你的构造函数中(尽管我不是那么喜欢)。

public static void main(String[] args) 
{ 
    findarea_class objtostring = new findarea_class(1.0,1.0); 
    System.out.println(objtostring); 
    objtostring.setelements(); 
}