如何在堆栈中使用ToString

问题描述 投票:0回答:1

我在编写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]
java stack tostring
1个回答
0
投票

所以我不得不根据您的描述做出一些推断。但基本上,如果未设置股票,则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
}
}
© www.soinside.com 2019 - 2024. All rights reserved.