【问题标题】:How to get multiple inputs using scanner in Java?如何在 Java 中使用扫描仪获取多个输入?
【发布时间】:2019-05-17 08:10:33
【问题描述】:

这是程序的输入。

3

1 45 5 3 5 Fizz Buzz FizzBuzz Nil

4 13 10 2 7 Ba Bi Be Bu

49 23 5 5 10 Oong Greeng Kattu Eswah

我想使用 Scanner 将所有这些行作为输入并将它们分成整数和字符串。使用扫描仪不是强制性的。也接受其他方法。

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 那么预期的输出是什么?
  • 欢迎来到 SO。我建议您阅读How to ask 文章,因为它为新手提供了有关如何编写问题的非常有用的信息。质量问题可帮助我们为您提供高质量的答案 - 请提供您的问题的 Minimal, Complete, and Verifiable example

标签: java string input int sentence


【解决方案1】:
Scanner scan = new Scanner("3\n" +
        "\n" +
        "1 45 5 3 5 Fizz Buzz FizzBuzz Nil\n" +
        "\n" +
        "4 13 10 2 7 Ba Bi Be Bu\n" +
        "\n" +
        "49 23 5 5 10 Oong Greeng Kattu Eswah");

ArrayList<String> strings = new ArrayList<>();
ArrayList<Integer> ints = new ArrayList<>();
while(scan.hasNext()){
    String word=scan.next();
    try {
        ints.add(Integer.parseInt(word));
    } catch(NumberFormatException e){
        strings.add(word);
    }
}

scan.close();

System.out.println(ints);
System.out.println(strings);

如果您希望 Scanner 使用 System.in 从控制台扫描输入,那么您需要一些将结束循环的触发字,例如 if("exit".equals(word)) break;

【讨论】:

    【解决方案2】:

    如果输入在文件中,我建议使用 BufferedReader 或 Files.lines(),对于扫描仪示例,请查看其他答案。下面是如何使用 BufferedReader 读取文件输入的示例。

    我建议使用this regex 来检查输入是 int 还是 String

    public static void main(String[] args) {
        List<Integer> ints = new ArrayList<>();
        List<String> strings = new ArrayList<>();
    
        try (BufferedReader br = new BufferedReader(
            new FileReader(new File("path/to/input/file"))
        )) {
          String line;
          while((line = br.readLine()) != null) {
            String[] parts = line.split(" ");
            for (String part : parts) {
              if (part.matches("(?<=\\s|^)\\d+(?=\\s|$)")) { // regex matching int
                ints.add(Integer.parseInt(part));
              } else {
                strings.add(part);
              }
            }
          }
    
        }
        catch (FileNotFoundException e) {
          System.out.println(e.getMessage());
        }
        catch (IOException e) {
          System.out.println(e.getMessage());
        }
    
        System.out.println("content of string = ");
        strings.forEach(string -> System.out.printf("%s ", string));
    
         System.out.println();
    
        System.out.println("content of ints = ");
        ints.forEach(string -> System.out.printf("%d ", string));
    
      }
    

    输出

    content of string = 
    Fizz Buzz FizzBuzz Nil Ba Bi Be Bu Oong Greeng Kattu Eswah 
    content of ints = 
    3 1 45 5 3 5 4 13 10 2 7 49 23 5 5 10 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 2015-01-19
      • 2012-12-06
      相关资源
      最近更新 更多