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:
package uk.ac.reading.cs2ja16.Glen.Stringtest;
import java.util.Arrays;
import java.util.Scanner;
public class stringnames {
public static String[] countNames (String names) {
// Create Scanner object
@SuppressWarnings("resource")
Scanner names1 =new Scanner(System.in);
// 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);
System.out.println(Arrays.toString(namesout));
}
}
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) {
System.out.println(name);
}
the println
method automatically adds a new line character at the end of the string that you want to print.
Stream API:
Arrays.stream(namesout).forEach(System.out::println);