简体   繁体   English

为字符串创建一个新行

[英]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:代码如下:

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.首先, countNames方法不需要参数,因此删除方法声明中的String names And delete the word null in your method call.并删除方法调用中的null一词。

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.现在,如果您使用的是 Java 8,您可以使用 for 循环或使用新 Stream API 中的方法之一。

I'll show you both ways.我会告诉你两种方式。

For loop: For循环:

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. println方法会自动在要打印的字符串的末尾添加一个新行字符。

Stream API:流API:

Arrays.stream(namesout).forEach(System.out::println);

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

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