簡體   English   中英

Java掃描器,將來自控制台的用戶輸入作為單獨的單詞輸入到數組列表中

[英]Java Scanner, taking user input from console into array list as separate words

我試圖將用戶輸入從控制台直接讀取到一個數組列表中,並用在兩側具有空格的每個單詞或實體分隔(默認行為)。 問題是我陷入了while循環中。 Scanner.next()一直在等待更多輸入,盡管我知道我想在用戶按return鍵后停止輸入輸入:

Scanner input = new Scanner(System.in);

    System.out.print("Enter a sentence: ");
    do {
        if (words.add(input.next());

    } while (input.hasNext());

    System.out.println(words);

我輸入了一行,除了我必須按CTRL-D來終止它(IE。表示輸入結束)。 我只想在句子的末尾按回車符'\\ n'時自動結束它。

使用split可能更簡單。

// read a line, split into words and add them to a collection.
words.addAll(Arrays.asList(input.nextLine().split("\\s+")));

您可以始終使用Console類,如下所示:

Console console = System.console();

System.out.print("Enter a sentence: ");

List<String> words = Arrays.asList(console.readLine().split("\\s+"));

System.out.println(words);

readline()方法應該處理\\ n問題。

如果您需要使用Scanner來讀取類型,則可以混合使用兩種類:

Scanner scanner = new Scanner(console.reader());

希望這可以幫助!

您可以調用input.hasNextLine和input.nextLine來獲得一行,然后為所獲得的行創建一個新的Scanner並使用現在的代碼。 不是最便宜的解決方案,而是一種簡單的實現方法,直到您提出更好的解決方案為止:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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