简体   繁体   中英

How do I use Scanner to read in a series of Strings from the keyboard, all on one line, and concatenate them

How do I use Scanner to read in a series of Strings from the keyboard, all on one line, and concatenate them.

Here is the code I have so far:

import java.util.Scanner;

public class Exam12Practice {

   public static void main(String[] args) 
   {
      Scanner input=new Scanner(System.in);
      String words="";
      System.out.println("enter a word");
      while(input.hasNext())
      {
         words = words.concat(input.next());
      }

      System.out.println(words);
   }
}

Your code already does what you are asking. To get it to work

Type in your words
Press Enter
Press CTRL-Z (^D on *nix systems)

Some points to note:

input.hasNext() will always return true for STDIN so just pressing Enter on its own won't work.

You could have used input.readLine() and split the words for your exercise.

Most people would probably prefer to use StringBuilder because of the improved performance it provides over String.concat .

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