Print with toString() method

我只是一个虾纸丫 提交于 2019-12-25 18:40:28

问题


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


回答1:


Add this method to your class (to override the toString() method):

@Override
public String toString() {
    return "Volume: " + volume(1) + "\n Calculate: " + calculate(1);
}

Note: @Override is optional: it's just communication and making sure you receive an error if you misspell the overridden method (toString()).

Also, why do you have parameters for volume and calculate if you don't use them? That's why I passed them a random number like 1 because it apparently doesn't matter what they are.




回答2:


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.



来源:https://stackoverflow.com/questions/22598294/print-with-tostring-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!