简体   繁体   English

如何使用扫描仪从键盘上读入一系列字符串,并将它们全部连接在一起

[英]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. 如何使用Scanner从键盘上读入一系列字符串,并将它们全部串联在一起。

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. input.hasNext()对于STDIN始终返回true,因此仅按Enter无效。

You could have used input.readLine() and split the words for your exercise. 您可以使用input.readLine()并为练习拆分单词。

Most people would probably prefer to use StringBuilder because of the improved performance it provides over String.concat . 大多数人可能更喜欢使用StringBuilder因为它提供了优于String.concat性能。

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

相关问题 如何使用扫描仪从同一行读取多个浮点数? - How do I read multiple floats from the same line with a scanner? 如何使用扫描仪一次仅读取整数行? - How to use Scanner to read only one line at a time with integers? 如何以一种方法获取从Java中的CSV文件读取的值,并以另一种方法使用它们? - How do I take values read from a CSV file in java in one method and use them in another method? 如何使用printf将单独的字符串格式化为一行? - How do I use printf to format separate strings into one line? 在 Java 中,如何使用 Scanner Class 在没有循环语句的情况下在一行中接收多个输入? - In Java, how do do I use Scanner Class to take in multiple inputs in one line without Loop Statements? 如何使用扫描仪从一行中逐字读取用户输入的内容? - How to read User input word by word from one line with scanner? 如何使用扫描仪搜索字符串数组? - How do I use Scanner to search an array of Strings? 如何使用扫描仪从文件中读取一行中的某个字符串? - How do I read a certain string on a line from a file, using scanner? 我如何知道扫描仪已读取所有输入? - How do I know that scanner has read all the inputs? 如何使用扫描仪从命令行读取文件 - How can I read a file from the command line using scanner
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM