简体   繁体   English

Java中的toString方法打印符号表

[英]toString method in Java to print a symbol table

I'm doing a project where I build a simple symbol table consisting of two arrays : ArrayOfKeys and ArrayOfValues. 我正在做一个项目,我在其中构建一个由两个数组组成的简单符号表:ArrayOfKeys和ArrayOfValues。 The keys are words and the values are the frequencies of each word in a text. 键是单词,值是文本中每个单词的频率。 I need to write a toString method for my ST class using this model: 我需要使用这个模型为我的ST类编写一个toString方法:

 public String toString() {
    // write your toString() method here
}

Suppose the words "aaa" and "bbb" are read from the text and inserted in the ST. 假设从文本中读取单词“aaa”和“bbb”并插入ST中。 The toString method will be called like this: toString方法将像这样调用:

StdOut.println("Let's see ST1 with 4 pairs key-val: " + st1);

where "st1" is an instance of the ST class. 其中“st1”是ST类的一个实例。 The output should be this: 输出应该是这样的:

Let's see ST1 with 4 pairs key-val: {'aaa': 1 , 'bbb': 1} 让我们看看ST1有4对key-val:{'aaa':1,'bbb':1}

As I see, the entire symbol table should be printed in the return statement of the toString() method, because it needs to return a String. 正如我所见,整个符号表应该在toString()方法的return语句中打印,因为它需要返回一个String。 I don't know how to do this, let alone in the format shown above. 我不知道怎么做,更不用说上面显示的格式了。

The best I could try was: 我能尝试的最好的是:

return (arrayOfKeys + ":" + arrayOfValues);

PS: I'm using Java version 1.8.0_121. PS:我使用的是Java版本1.8.0_121。

One relatively neat (IMHO) approach is to create a stream of the indexes the arrays have and let Collectors.joining do the heavy lifting for you: 一个相对简洁(IMHO)的方法是创建数组所拥有的索引流,让Collectors.joining为您做繁重的工作:

String result = 
    IntStream.range(0, arrayOfKeys.length)
             .mapToObj(i -> "'" + arrayOfKeys[i] + "': " + arrayOfValues[i])
             .collect(Collectors.joining(" , ", "{", "}"));

You can try using StringBuilder to generate the string. 您可以尝试使用StringBuilder生成字符串。 Code should look something like below: 代码应如下所示:

public String toString() {
    StringBuilder sb = new StringBuilder("Let's see ST1 with 4 pairs key-val: {");
    for(int i = 0; i< arrayOfKeys.size();i++) {
        sb.append('\'' + arrayOfKeys[i] + '\': ');
        sb.append(String.valueOf(arrayOfValues[i]));
        if(i!=arrayOfKeys.size() -1) {
            sb.append(" , ");
        }
    }
    sb.append("}");
    return sb.toString();
}
 public String toString() {
    String results = "{";
    for (int i = 0; i < arrayOfKeys.length; i++){
        results += "'"+arrayOfKeys[i]+"' : "+arrayOfValue[i]+",";
    }
    results+="}";

    return results;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM