【问题标题】:Java Scanner, taking user input from console into array list as separate wordsJava Scanner,将用户从控制台输入到数组列表中作为单独的单词
【发布时间】:2011-11-29 12:02:21
【问题描述】:

我正在尝试将来自控制台的用户输入直接读取到一个数组列表中,并由每个单词或实体分隔,两边都有空格(默认行为)。问题是我被困在一个while循环中。 Scanner.next() 一直在等待更多输入,尽管我知道我想在用户按下返回后停止输入输入:

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 来终止它(即,表示输入结束)。我只想在句尾按下回车'\n'字符时自动结束它。

【问题讨论】:

    标签: java arraylist java.util.scanner next


    【解决方案1】:

    根据需要使用 split 可能更简单。

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

    【讨论】:

      【解决方案2】:

      你总是可以使用 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());
      

      希望这会有所帮助!

      【讨论】:

        【解决方案3】:

        您可以调用 input.hasNextLine 和 input.nextLine 来获取一行,然后为您获取的行创建一个新的 Scanner 并使用您现在拥有的代码。不是最便宜的解决方案,而是一种实现它的简单方法,直到你想出一个更好的解决方案:-)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-12-02
          • 2013-02-27
          • 2015-01-26
          • 2012-08-05
          • 2018-08-03
          • 2019-07-07
          • 2014-11-19
          相关资源
          最近更新 更多