在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程序中正确地读取和处理标准输入数据。