简体   繁体   English

Java:如何将同一字符串中的两个单词输出到单独的行上?

[英]Java: How to output two words in the same string onto separate lines?

I am trying to enter the first and last name in one string and then display the first and last name on separate lines. 我试图在一个字符串中输入名字和姓氏,然后在单独的行中显示名字和姓氏。 I thought the nextLine(); 我以为nextLine(); command would work but is not displaying the first and last name on separate lines 命令会起作用,但不会在单独的行中显示名字和姓氏

    String full_name;

    System.out.println("Please enter your first and last name?");

     full_name = c.nextLine();

    System.out.printf("Your name is: "+ full_name);

你可以尝试...

System.out.print("Your name is: "+ full_name.replace(" ", "\n"));

Presuming that c is a Scanner set to listen to System.in , then by virtue of it being on the input stream, it wouldn't have an effect on the output stream. 假设c是设置为侦听System.inScanner ,则由于它在输入流上,因此不会对输出流产生影响。

Instead, if you wanted to print the first and last name that was entered, and we presume that a first and last name is separated by a single space (may want logic for middle names), you can write this. 相反,如果您要打印输入的名字和姓氏,并且我们假设名字和姓氏之间用一个空格分隔(可能需要中间名逻辑),则可以编写此代码。

String[] brokenName = full_name.split(" ");
System.out.printf("Your name is:\n%s\n%s", full_name[0], full_name[1]);

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

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