简体   繁体   中英

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(); 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.

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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