在Java編程中,通常使用Scanner類來讀取標(biāo)準(zhǔn)輸入(stdin)。以下是一些最佳實(shí)踐:
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.");
}
遵循以上最佳實(shí)踐,可以確保在Java程序中正確地讀取和處理標(biāo)準(zhǔn)輸入數(shù)據(jù)。