微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何打印用大括号分隔的数组列表逗号?

如何解决如何打印用大括号分隔的数组列表逗号?

如何在Java中打印用大括号分隔的字符串列表逗号?例如,一个有三个成员“母亲”,“父亲”和“女儿”的家庭应打印为

There is a family consists of { Mother,Father,Daughter }

或空家族为

There is a family consists of { }

我写了这个,但是它不能打印字符串列表:

String[] family = {" "};
String separator = "";
System.out.print("{ ");
for (String word : family) {
    System.out.print(separator);
    System.out.print(word);
    separator = " ";
}
System.out.print(" }");

谢谢!

解决方法

尝试以下StringJoiner可以解决您的要求

        //Define the Array List
        List<String> family = Arrays.asList("Mother","Father","Daughter");

        //StringJoiner class joins elements with given saperator and 
        //Start and end characters of the List
        //Below Joiner joins list items with',' character and
        //add '{' at start of the list and '}' at end of the list 
        StringJoiner strJoin = new StringJoiner(",","{","}");

        //Below is the simplified Lambda expression in Java8
        //Traversing family list by forEach
        //(s) denotes every element in that list and
        //we are just adding that s into strjoin 
        family.forEach((s)->strJoin.add(s));

        //printing the string joiner object  
        System.out.println(strJoin);

输出: {母亲,父亲,女儿}

希望以上说明可以帮助您理解代码

,

(如所承诺的)这里有一些提示可以帮助您完成您的尝试...

这是您的代码当前的样子:

  String[] family = {" "};
    String separator = "";
    System.out.print("{ ");
    for (String word : family) {
        System.out.print(separator);
        System.out.print(word);
        separator = " ";
    }
    System.out.print(" }");
}

我假设这是 inside 一种main方法,其正确签名是 inside a class

  1. family声明不正确:

     String[] family = {" "};
    

    这不是您表示空数组的方式。 (它实际上是一个包含一个字符串的数组,由一个空格组成。这可以解释您的一些困难!)

    Java中的空字符串数组可以声明为:

    String[] family = {};
    String[] family = new String[0];
    String[] family = new String[]{};
    
  2. 分隔符不应为""。应该是逗号。 (不完全是,但是尝试一下。)

  3. 您无需在循环中更改分隔符。分隔符应始终为逗号。

如果您按照上述步骤进行操作,则将获得如下输出:

{  }
{,Mother }
{,Mother,Father }
{,Father,Daughter }

还有两个问题需要解决。

  1. 仅用逗号作为分隔符是不正确的。 (您应该能够弄清楚该怎么做。)

  2. 只要列表为非空,我们就会有一个多余的前导逗号。这个比较棘手。问题在于该顺序:

        System.out.print(separator);
        System.out.print(word);
    

    假设我们现在正在打印的单词之前有一个“单词”。但是,当我们位于列表的开头时,情况并非如此。

处理多余逗号的一种方法是在列表的开头不输出分隔符。但是如何?

提示在列表的开头使用标志变量true,并在打印第一个元素后将其更改为false。 (并使用该标志来决定是否需要输出分隔符。)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。