[英]How do I use Scanner to read in a series of Strings from the keyboard, all on one line, and concatenate them
如何使用Scanner从键盘上读入一系列字符串,并将它们全部串联在一起。
这是我到目前为止的代码:
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);
}
}
您的代码已经满足您的要求。 为了使其工作
Type in your words
Press Enter
Press CTRL-Z (^D on *nix systems)
需要注意的几点:
input.hasNext()
对于STDIN
始终返回true,因此仅按Enter无效。
您可以使用input.readLine()
并为练习拆分单词。
大多数人可能更喜欢使用StringBuilder
因为它提供了优于String.concat
性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.