在Java編程中,通常使用Scanner類來讀取標準輸入(stdin)。以下是一些最佳實踐:
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
String line = scanner.nextLine();
try {
int num = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter an integer.");
}
scanner.close();
try (Scanner scanner = new Scanner(System.in)) {
int num = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter an integer.");
}
遵循以上最佳實踐,可以確保在Java程序中正確地讀取和處理標準輸入數據。