【问题标题】:How to use ToString in Stacks如何在堆栈中使用 ToString
【发布时间】:2020-05-29 20:08:50
【问题描述】:

我无法编写一个 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】:

所以我不得不从你的描述中做出一些推论。但基本上,如果未设置库存,则 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
}
}

【讨论】:

    猜你喜欢
    • 2019-07-31
    • 2018-04-04
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多