如何正确调用toString

时间:2016-07-26 21:09:05

标签: java tostring

我试图在Box类中创建一个toString方法来调用BoxTest类。我已经设置了我想要调用的方法(getLengthgetHeightgetWidthcalculateAreacalculateVolume),这些方法可以自行运行,但在调用toString时,我不确定如何使用它们。

这是我当前代码的pastebin(http://pastebin.com/Ex520ST6)。

public class Box
{
    private double length = 1.0;
    private double width = 1.0;
    private double height = 1.0;

    public Box(double length, double width, double height) // constructor with thrown exceptions
    {
        if (length <= 0)
            throw new IllegalArgumentException("Values must be higher than 0");

        if (width <= 0)
            throw new IllegalArgumentException("Values must be higher than 0");

        if (height <= 0)
            throw new IllegalArgumentException("Values must be higher than 0");

        this.length = length;
        this.width = width;
        this.height = height;
    }

    public void setLength(double length)
    {
        if (length <= 0)
            throw new IllegalArgumentException("Values must be higher than 0");

        this.length = length;
        System.out.println("The new length is: " + length);

    }
    public double getLength()
    {
        System.out.println("The length is: " + length);
        return length;
    }
    public void setWidth(double width)
    {
        if (width <= 0)
            throw new IllegalArgumentException("Values must be higher than 0");

        this.width = width;
        System.out.println("The new width is: " + width);
    }
    public double getWidth()
    {
        System.out.println("The width is: " + width);
        return width;
    }
    public void setHeight(double height)
    {
        if (height <= 0)
            throw new IllegalArgumentException("Values must be higher than 0");

        this.height = height;
        System.out.println("The new height is: " + height);
    }
    public double getHeight()
    {
        System.out.println("The height is: " + height);
        return height;
    }
    public double calculateArea()
    {
        double area = (double) (2*length*width + 2*length*height + 2*width*height);
        System.out.println("The area is: " + area);
        return area;
    }
    public double calculateVolume()
    {
        double volume = (double) length*width*height;
        System.out.println("The volume is: " + volume);
        return volume;
    }
    public String toString()
    {
        return String.format("The length is %f, the width is %f, the height is %f, the area is %f, the volume is %f,");
    }
}

BoxTest

public class BoxTest
{
    public static void main (String[] args)
    {
        Box[] boxes = new Box[4];

        boxes[0] = new Box(1.0,2.0,3.0);
        boxes[1] = new Box(4.0,5.0,6.0);
        boxes[2] = new Box(1.0,7.0,8.0);
        boxes[3] = new Box(1.0,9.0,9.0);

        for (Box theBoxes : boxes)
        {

            System.out.printf(theBoxes.getLength(),theBoxes.getWidth(),theBoxes.getHeight(),theBoxes.calculateArea(),theBoxes.calculateVolume().toString());

        }

        boxes[3].setLength(11.0); // debug
    }
}
  1. 我是在正确的轨道上,一般是
  2. 我应该在"%s"标题
  3. 中使用toString说明符吗?
  4. 我是否还需要printf中的格式说明符,如果是,则应该是%s%f,因为我的方法是double类型。
  5. 谢谢!

1 个答案:

答案 0 :(得分:3)

toString()覆盖应该返回一个String值,而不依赖于System.out.printf()的外部使用(该方法当然可以在类中使用,但是类应该返回完全格式化的String,而不是包含%s等格式化程序的class Animal { public String name; public int numlegs; public double weight; // ... @Override public String toString() { return String.format("Animal, name: %s, legs: %d, weight: %d", name, numLegs, weight); } } 。示例实现如下。

String

然后,您只需调用toString()方法即可检索对象的完整printf()表示。

鼓励使用String而不是大规模toString()连接,因为它可以实现更清晰的代码(至少是IMO)。

侧面说明:

  1. 您的printf()方法调用String,但未提供应替换printf()格式的格式化程序的值。
  2. String的调用应该将格式public void getNotifications() { Observable.concat(getCashedNotifications(), downloadNotification()) .subscribe(new Action1<List<Notification>>() { @Override public void call(List<Notification> notifications) { setSize(notifications.size() + ""); } }); } private Observable<List<Notification>> getCashedNotifications() { return Observable.just(mRealm.copyFromRealm(mRealm.where(Notification.class).findAll())); } private Observable<List<Notification>> downloadNotification() { return mApiHandler.createRetrofitService(NotificationServices.class) .getNotificationByUser(10) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .doOnNext(new Action1<NotificationResponse>() { @Override public void call(final NotificationResponse notificationResponse) { setLoading(false); mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealmOrUpdate(notificationResponse.getResult().getData().getNotifications()); } }); } }) .map(new Func1<NotificationResponse, List<Notification>>() { @Override public List<Notification> call(NotificationResponse notificationResponse) { if (notificationResponse.getResult() != null) { return notificationResponse.getResult().getData().getNotifications(); } else { return new ArrayList<>(); } } }); } 作为第一个参数,将值作为剩余参数。