- 使用正則表達式對輸入進行匹配和處理。
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\s*,\\s*");
while (scanner.hasNext()) {
String input = scanner.next();
System.out.println(input);
}
- 將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();
}
- 使用自定義的分隔符來讀取輸入。
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(Pattern.compile("[,.;\\s]+"));
while (scanner.hasNext()) {
String input = scanner.next();
System.out.println(input);
}
- 使用Scanner的hasNextLine()和nextLine()方法來逐行讀取輸入。
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
- 使用Scanner的nextInt()、nextDouble()等方法來讀取不同類型的數據。
Scanner scanner = new Scanner(System.in);
int intValue = scanner.nextInt();
double doubleValue = scanner.nextDouble();
String stringValue = scanner.next();