我想知道是否有一种简单的方法来显示错误字符或无效输入数据的错误。
public static void main(String[] args) {
// Step 1: Create new Scanner object.
Scanner input = new Scanner(System.in);
// Step 2: Prompt the user to enter today's day.
System.out.print("Enter today’s day as an Integer (0-6): ");
int Today = input.nextInt();
// Step 3: Prompt the user to enter the number of days elapsed since today.
System.out.print("Enter the number of days elapsed since today as an Integer: ");
int DaysElapsed= input.nextInt();
// Step 4: Compute the future day.
int FutureDay = (Today + DaysElapsed) % 7;
// Step 5: Printing the results.
// Step 5.1: Today's day result depending the case.
System.out.print("Today is ");
// Step 5.2: Future day result depending the case.
System.out.print(" and the future day is ");
最佳答案
因为您只期望 scanner.nextInt()
中的“int”它将抛出 InputMismatchException
异常(exception)。因此您可以轻松验证 int
的输入像这样 -
try {
int Today = input.nextInt();
int DaysElapsed= input.nextInt();
} catch (InputMismatchException){
System.err.println("Input is not an integer");
}
Scanner.nextInt()还抛出NoSuchElementException
和IllegalStateException
异常(exception)情况
此外,您可以使用条件( today>=1 && today=<31
)验证输入日期是否有效
关于java - 当用户输入错误字符或无效输入数据时如何显示 "print"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56119219/