java—如何在堆栈中使用tostring

w8rqjzmb  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(357)

我在编写一个tosting方法来显示数组中的大小时遇到了问题,请去掉堆栈中的括号

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]
8qgya5xd

8qgya5xd1#

所以我不得不从你的描述中做出一些推论。但是基本上,如果没有设置股票,tostring返回空的,没有括号,如果已经设置了描述符,则将数组中的数字与其描述符放在一起。如果您的对象看起来不同,您可能需要进行一些调整,但关键是使用数组的内容,而不是整个数组。
如果我误解了你所说的堆栈,这是没有帮助的,请解释或包括您的类,要么我可以修改这个,否则我会撤回它。

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
}
}

相关问题