简体   繁体   English

java - 如何将数组更改为每个名称在java中单独一行的字符串?

[英]How to change an arrays into a String with each name on a separate line in java?

I am a newbie to java and I am trying to begin with a simple task- list a group of names into alphabetical order.我是 Java 的新手,我试图从一个简单的任务开始 - 按字母顺序列出一组名称。 Currently, my code is fine:目前,我的代码很好:

import java.util.Arrays;
public class CLASSROOM_SSONG {
    String[] names = {"Joe", "Bob", "Andy"};
    public static void main(String args[]) {
        CLASSROOM_SSONG x =new CLASSROOM_SSONG();
        x.roster();
    }

    public String [] roster() {
        Arrays.sort(names);
        System.out.println(Arrays.toString(names));
        return names;

    }
}

However, this code returns an ARRAY with the brackets, and I prefer there to be names on separate lines without the brackets.但是,此代码返回一个带括号的 ARRAY,我更喜欢在没有括号的单独行上有名称。 This is what I am looking for it to return:这就是我正在寻找它返回的内容:

Andy
Bob
Joe

How would I do that?我该怎么做? I thought 'println' would give each a separate line, but now I am stuck.我以为 'println' 会给每个单独的一行,但现在我被卡住了。 I can't think of a way without having to print each name separately, which defeats the purpose completely.我想不出一种方法,而不必单独打印每个名称,这完全违背了目的。

All help would be appreciated!所有帮助将不胜感激!

Oh, by the way, when I search for answers, sometimes I get crazy things with a ton of helper methods.哦,顺便说一句,当我搜索答案时,有时我会用大量的辅助方法得到一些疯狂的东西。 I Prefer simple ones that I can read :)我更喜欢简单的,我可以阅读:)

The easiest way is to output the names one after the other.最简单的方法是一个接一个地输出名称。 This is possible with a simple for-loop or any iterators.这可以通过简单的 for 循环或任何迭代器实现。

Simple For-loop:简单的 For 循环:

String[] names = {"Joe", "Bob", "Andy"};

for (String name : names) {
  System.out.println(name);
}

You need to go through the array and print out each name with:您需要遍历数组并打印出每个名称:

for(String name: names) {
  System.out.println(name);
}

or或者

for (int i=0; i < names.length; i++){
   System.out.println(names[i]);
}
    String array;

    for(int i=0;i<names.length;++i){
       array+=names[i]+"\n";
    } 
    System.out.println(array);

Maybe this is not the best approach!也许这不是最好的方法!

Try this.尝试这个。

    Arrays.sort(names);  // sort first

    System.out.println(String.join("\n", Arrays.asList(names)));
    // Arrays.asList(names) converts the string into an ArrayList   

You can use JAVA 8 to sort and print each element on a new line.您可以使用JAVA 8对每个元素进行排序并在新行上打印。

import java.util.Arrays;
public class CLASSROOM_SSONG {
    String[] names = {"Joe", "Bob", "Andy"};
    public static void main(String args[]) {
        CLASSROOM_SSONG x =new CLASSROOM_SSONG();
        x.roster();
    }

    public void roster() {
        // sort the array and print it to new line
        Arrays.stream(names).sorted().forEach(System.out::println);
    }
}

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

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