我是一名新的程序员,由于我是学生,我对异常处理非常缺乏经验。我正在编写一个程序,让用户可以安排从1到6点钟开始的约会。如果用户输入除整数之外的任何值,我希望程序告诉用户他/她的输入有错误,并且应该将其更改为整数值,而不是double,String,char等。是我的代码如下:
boolean created = false;
while (!created) {
// Asks when you want your appointment
System.out.println("When would you like your appointment?");
int userTime = input.nextInt();
try {
/**
* I really do not know what to put in here. If the user inputs things like
* letters and symbols and doubles or floats, etc. I want the program to send a
* message to the user saying that an integer value must enter an integer.
*/
userTime = input.nextInt();
} catch (InputMismatchException ime) {
System.out.println("Error! Please enter an integer from 1 to 6. Letters and symbols are not allowed");
}
/*
* Checks if the time value is either not in range and not taken- than lets you
* pass on to create the appointment and add it into the array
*/
if (userTime < 1 || userTime > 6) {
System.out.println("Time value not in range");
} else if (appointments[userTime] != null) {
System.out.println("Time already taken");
} else {
// Adds username into array of Appointments
created = true;
apTotal++;
appointments[userTime] = name;
}
}
另外,顺便说一下 - 我不完全确定它是否实际上是一个inputMisMatch异常或其他东西,但如果它不是,请告诉我,因为我是初学者。 谢谢大家!
答案 0 :(得分:0)
所以从你的代码片段我猜你正在使用某些类型的扫描仪/ BufferedReader设置。检查整数输入的好方法是使用它们 “Integer.parseInt()”函数(参见:https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String))如果这不能将输入解析为有效整数,它将抛出一个“NumberFormatException”,然后您可以捕获并处理它!希望这有帮助!