0

I am having trouble writing a ToSting method to show the size in the array get rid of the brackets in the Stacks

expected:

RED=

GREEN=

BLUE=

SIZESINSTOCK=S:0 M:0 L:0 XL:0 BIG:0

SOLDOUT=S:0 M:0 L:0 XL:0 BIG:0

But was:

RED=[]

GREEN=[]

BLUE=[]

SIZESINSTOCK=[0, 0, 0, 0, 0]

SOLDOUT=[0, 0, 0, 0, 0]
Dmitry Demin
  • 2,006
  • 2
  • 15
  • 18
Tad Ye
  • 1
  • 1

1 Answers1

0

So I have had to make some inferences from your description. But basically, the toString returns empty without brackets if the stock was not set and puts together the numbers from the array with their descriptors if those have been set. If your object looks different, you may need to adapt a bit, but the key would be to use the array's contents, not the array as a whole.

If I have misunderstood what you mean by stacks and this is no help, please explain or include your class, and either I can adapt this or I will withdraw it.

public class KeepStock {
private int[] stock = new int[5]; //array to hold different stock counts
private String name; //kind of stock
private boolean stockSet = false; //whether stock was set at all, or if it is empty
public KeepStock(String name) { //constructor
    this.name = name;
}
public void setStock(int small, int medium, int large, int extra, int big) { //sets stock counts in array
    stock[0] = small;
    stock[1] = medium;
    stock[2] = large;
    stock[3] = extra;
    stock[4] = big;
    stockSet = true; //now they are actually there
}
@Override
public String toString() {
    String result = name + "=";
    if (stockSet) { //add stocks, otherwise leave blank
        String[] stockNames = {
            "S:",
            " M:",
            " L:",
            " XL:",
            " BIG:"
        };
        for (int i = 0; i < 5; i++) {
            result += stockNames[i] + stock[i]; //add the name and count
        }
    }
    return result;
}
public static void main(String[] args) {
    KeepStock redStock = new KeepStock("RED");
    System.out.println(redStock); //says RED=
    KeepStock sizesInStock = new KeepStock("SIZESINSTOCK");
    sizesInStock.setStock(1, 2, 3, 4, 5);
    System.out.println(sizesInStock); //says SIZESINSTOCK=S:1 M:2 L:3 XL:4 BIG:5
    //sold out, green, and blue would be similar
}
}
Jeremy Kahan
  • 3,796
  • 1
  • 10
  • 23