我想知道是否有一种简单的方法来显示错误字符或无效输入数据的错误。
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 ");发布于 2019-05-14 04:20:12
因为你在这里只期待来自scanner.nextInt()的'int‘,所以它将抛出一个InputMismatchException异常。这样你就可以很容易地在这里验证你对int的输入了-
try {
int Today = input.nextInt();
int DaysElapsed= input.nextInt();
} catch (InputMismatchException){
System.err.println("Input is not an integer");
} Scanner.nextInt()还抛出NoSuchElementException和IllegalStateException异常,此外,您可以使用条件(today>=1 && today=<31)来验证输入日期是否有效
发布于 2019-05-14 04:22:00
使用nextInt(),您已经将允许的值过滤为整数。但是,如果您希望用户在有限的范围内输入值,则可以使用以下内容:
int Today = 0;
if (input.hasNextInt()) {
if (input.nextInt() < 32 && input.nextInt() > 0) { //should be between 0-32
Today = input.nextInt();
} else {
throw new Exception("Number must be between 0-32");
}
}编辑:
如果您想在出错时继续:
int Today = 0;
if(input.hasNextInt()) {
Today = input.nextInt();
while (!(Today > 0 && Today < 32)){
System.out.println("Number must be between 0-32");
Today = input.nextInt();
}
}https://stackoverflow.com/questions/56119219
复制相似问题