megasxrl megasxrl - 1 year ago 68
Java Question

creating a new line for string

made a program that counts and outputs users based on user input. I want the program to display the names one below the other with the line break but stuck on how to. the code is below:

import java.util.Arrays;
import java.util.Scanner;

public class stringnames {

public static String[] countNames (String names) {

// Create Scanner object
Scanner names1 =new Scanner(;

// Read a string
String read= names1.nextLine();

// Split string with space
String numPeople[]=read.trim().split(" ");

System.out.println("The Number of names inputted is: "+ numPeople.length);

return numPeople;

public static void main(String[ ] args){

System.out.println("Enter the amount of names you want(make sure you make space for each name):\n");
String[] namesout = countNames(null);

Answer Source

First of all, the countNames method does not need a parameter, so delete that String names thingy in the method declaration. And delete the word null in your method call.

Now, you can either use a for loop or use one of the methods in the new Stream API if you're using Java 8.

I'll show you both ways.

For loop:

for (String name: namesout) {

the println method automatically adds a new line character at the end of the string that you want to print.

Stream API:;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download