简体   繁体   中英

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. 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. 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. 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.

Simple For-loop:

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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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