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