使用toString()方法打印 [英] 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 ;
}
}
在上面的代码中,如何制作toString()方法,所以我可以返回volume的值并计算??? 我是Java的新手,所以请尽可能简单
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
推荐答案
将此方法添加到您的类中(以覆盖toString()
方法):
Add this method to your class (to override the toString()
method):
@Override
public String toString() {
return "Volume: " + volume(1) + "\n Calculate: " + calculate(1);
}
注意:@Override
是可选的:它只是通信,如果错拼了覆盖的方法(toString()
),请确保收到错误.
Note: @Override
is optional: it's just communication and making sure you receive an error if you misspell the overridden method (toString()
).
此外,为什么不使用volume
和calculate
的参数?这就是为什么我将诸如1
之类的随机数传递给他们的原因,因为它们显然无关紧要.
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.
这篇关于使用toString()方法打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!