[英]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.