In this part of code:
System.out.println("Alunos aprovados:");
String[] aprovados = {"d", "a", "c", "b"};
List<String> list = new ArrayList();
for (int i = 0; i < aprovados.length; i++) {
if (aprovados[i] != null) {
list.add(aprovados[i]);
}
}
aprovados = list.toArray(new String[list.size()]);
Arrays.sort(aprovados);
System.out.println(Arrays.asList(aprovados));
An example result of System.out.println is:
[a, b, c, d]
How could I modify the code above if I want a result like below?
a
b
c
d
Or, at least:
a,
b,
c,
d
To print the array elements on a separate line, we can use the printf command with the %s format specifier and newline character \n in Bash. @$ expands the each element in the array as a separate argument. %s is a format specifier for a string that adds a placeholder to the array element.
Use the join() method to combine the array into one string and separate each entry by by <br> to print array on separate lines in JavaScript.
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
Iterate through the elements, printing each one individually.
for (String element : list) {
System.out.println(element);
}
Alternatively, Java 8 syntax offers a nice shorthand to do the same thing with a method reference
list.forEach(System.out::println);
or a lambda
list.forEach(t -> System.out.println(t));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With