用括号和逗号打印枚举列表

时间:2021-04-25 21:41:22

I can print my enum list using a for each loop, it prints nice and clean. But I want to print it with the brackets and commas in beteween each element. Here is what i tried and the output produced. How can I produce the brackets and commas? [SU, MO, TU, WE, TH, FR, SA]

我可以使用for each打印我的枚举列表,它打印得很干净。但我想用每个元素之间的括号和逗号打印它。这是我尝试和产生的输出。如何生成括号和逗号? [SU,MO,TU,WE,TH,FR,SA]

public class ExerciseLoop {
    public static void main(String[] args) {
        Day fDay = Day.SU;

        System.out.println("F day: " + fDay);
        System.out.print("All days ");

        for (Day el : Day.values()) {
            System.out.print(el+ " ");
        }

        System.out.println();
        System.out.println(Day.values());
    }

    public enum Day {
        SU, MO, TU, WE, TH, FR, SA;
    } 
}

Ouput

F day: SU
All days SU MO TU WE TH FR SA 
[LExerciseLoop$Day;@15db9742

1 个解决方案

#1


3  

There are several ways to do so. First a manual approach:

有几种方法可以做到这一点。首先是手动方法:

// Build the text
final StringBuilder result = new StringBuilder();
result.append("[");
for (final Day el : Day.values()) {
    result.append(el).append(", ");
}
// Remove the extra ", "
result.setLength(result.length() - 2);
result.append("]");
System.out.println(result.toString());

Of course you can evade the "removement" of the extra ", " by simply adding a counter. If the last element is reached, don't add it.

当然,你可以通过简单地添加一个计数器来逃避额外“,”的“删除”。如果到达最后一个元素,请不要添加它。

However I'd like to show you a new class (from Java 8) which was made exact for this purpose, the StringJoiner!

但是我想向你展示一个新类(来自Java 8),它是为了这个目的而准确的,StringJoiner!

final StringJoiner result = new StringJoiner(",", "[", "]");
for (final Day el : Day.values()) {
    result.add(el.toString());
}
System.out.println(result.toString());

You can find more information in the documentation: JavaAPI#StringJoiner

您可以在文档中找到更多信息:JavaAPI#StringJoiner

#1


3  

There are several ways to do so. First a manual approach:

有几种方法可以做到这一点。首先是手动方法:

// Build the text
final StringBuilder result = new StringBuilder();
result.append("[");
for (final Day el : Day.values()) {
    result.append(el).append(", ");
}
// Remove the extra ", "
result.setLength(result.length() - 2);
result.append("]");
System.out.println(result.toString());

Of course you can evade the "removement" of the extra ", " by simply adding a counter. If the last element is reached, don't add it.

当然,你可以通过简单地添加一个计数器来逃避额外“,”的“删除”。如果到达最后一个元素,请不要添加它。

However I'd like to show you a new class (from Java 8) which was made exact for this purpose, the StringJoiner!

但是我想向你展示一个新类(来自Java 8),它是为了这个目的而准确的,StringJoiner!

final StringJoiner result = new StringJoiner(",", "[", "]");
for (final Day el : Day.values()) {
    result.add(el.toString());
}
System.out.println(result.toString());

You can find more information in the documentation: JavaAPI#StringJoiner

您可以在文档中找到更多信息:JavaAPI#StringJoiner