基本的に、入力が整数かどうかを確認するには、次の while ループが必要です。配列を指しているため、小数を含めることはできません。入力された値が 10 進数の場合、ユーザーに再度プロンプトを表示する必要があります。問題は、このコードで while ループが始まる前に 2 つのプロンプトが表示されることです。何か案は?
System.out.print("Enter month (valid values are from 1 to 12): ");
Scanner monthScan = new Scanner(System.in);
int monthInput = monthScan.nextInt();
// If the month input is below 1 or greater than 12, prompt for another value
while(monthInput<1 || monthInput>12 || !monthScan.hasNextInt())
{
System.out.print("Invalid value! Enter month (valid values are from 1 to 12): ");
monthInput = new Scanner(System.in).nextInt();
}
ありがとう
編集:現在の出力は次のようになります。
Enter month (valid values are from 1 to 12): 2
2
有効な値であるにもかかわらず、2 を 2 回入力しなければならなかったことに注目してください。