Home > other >  How to display all information in toString
How to display all information in toString

Time:01-28

I have two classes: Position and Order. In Position class, fields like: name, price. In Order class field: quantity. My problem is how to display: name, price and quantity together in Order class. I thought about delete arraylist and make another one with position and quantity but I doubt it would help me.

package programming.com.pl;

public class Position  {

private String name;
private double price = 0;


public Position(String name, double price){
    this.name = name;
    this.price = price;
}

public double getPrice() {
    return price;
}

public String toString(){
    String str = String.format("%4s,%4s", name,price);
    return  str;
}
}

public class Order {
private int quantity;
final private ArrayList<Position> positions = new ArrayList<Position>();
private int addedPosition;


public Order(int quantity) {
    this.quantity = quantity;
}

private double calculateProduct() {
    double sum = 0;
    for (int i = 0; i < positions.size(); i  ) {
        sum = positions.get(i).getPrice();
    }
    return sum;
}

double sumOrder() {
    double sum = 0;
    for (Position x : positions) {
        sum  = calculateProduct();
    }
    return sum;
}


void addPosition(Position p) {
    if (!positions.contains(p)) {
        positions.add(p);
    } else {
        quantity  ;
    }
}

void deletePosition(int index) {
    positions.remove(index);
}


public String toString() {
    System.out.println("Order is: ");
    for (Position p : positions) {
        System.out.println(positions.toString());
    }
    return "Order sum is: "   sumOrder();
}
}

CodePudding user response:

You already are overriding toString method in Position class so you just need to call that toString method on the position object when iterating the position objects from inside your Order class' toString() method.

And as @Federico points out in the comments you shouldn't System.out.println from toString methods. Just append to a string the details you require displaying and return that string.

You can achieve your desired result like so:

public class Position {
    .
    .
    @Override
    public String toString() {
        return String.format("%4s,%4s\n", name, price);
    }
}

public class Order {
    .
    .
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("Order details: \n");
        sb.append("Quantity: ").append(quantity).append("\n");
        for (Position p : positions) {
            sb.append(p);
        }
        sb.append("Order sum is: ").append(sumOrder());
        return sb.toString();
    }
}
  •  Tags:  
  • Related