溫馨提示×

Java中Scanner類的高級用法有哪些

小樊
109
2024-08-07 03:45:20
欄目: 編程語言

  1. 使用正則表達式對輸入進行匹配和處理。
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\s*,\\s*"); // 使用逗號作為分隔符
while (scanner.hasNext()) {
    String input = scanner.next();
    System.out.println(input);
}
  1. 將Scanner與try-with-resources結合使用,確保資源的正確關閉。
try (Scanner scanner = new Scanner(new File("input.txt"))) {
    while (scanner.hasNext()) {
        String input = scanner.next();
        System.out.println(input);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
  1. 使用自定義的分隔符來讀取輸入。
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(Pattern.compile("[,.;\\s]+"));
while (scanner.hasNext()) {
    String input = scanner.next();
    System.out.println(input);
}
  1. 使用Scanner的hasNextLine()和nextLine()方法來逐行讀取輸入。
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    System.out.println(line);
}
  1. 使用Scanner的nextInt()、nextDouble()等方法來讀取不同類型的數據。
Scanner scanner = new Scanner(System.in);
int intValue = scanner.nextInt();
double doubleValue = scanner.nextDouble();
String stringValue = scanner.next();

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女