如何在 Java 中使用扫描仪获取多个输入?

How to get multiple inputs using scanner in Java?

这是程序的输入。

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 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);

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

如果输入在文件中,我建议使用 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