Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

java - Print with toString() method

class Box
{
    // Instance Variables
    double length ,ipsos ;
    double width ,mikos ;
    double height ,platos;
    // Constructors
    public Box ( double side )
    {
        width = side ;
        height = side ;
        length = side ;
    }
    public Box ( double x , double y , double z)
    {
        platos = y ;
        ipsos = z;
        mikos = x ;
    }

    // Methods
    double calculate(double praksi)
    {
        return 2 * ( width * height +
        width * length +
        height * length ) ;
    }
    double volume(double emvadon)
    {
        return platos*ipsos*mikos ;
    }

}

In the upper code, how can I make a toString() method, so I can return the values of volume and calculate ??? Im new with java so be as simple as you can please

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not too sure what the parameters of the methods 'calculate', 'volme' are for? If you're looking to override the default toString method, so when you call System.out.println(new Box(1,2,3)): it prints out the volume, and value calculate returns for the box then the following should work:

Box b = new Box(1,2,3);
System.out.println(b);

Then the following should work:

@Override
public String toString()
{
  return "Volume: " + volume(0.0) + ", calculate: " + calculate(0.0);
}

This would print the volume and whatever calculate returns, both clearly labelled.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...