我如何使用 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
。
关于java - 我如何使用扫描仪从键盘读取一系列字符串,全部在一行上,并将它们连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12665835/