簡體   English   中英

如何使用掃描儀從鍵盤上讀入一系列字符串,並將它們全部連接在一起

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM