Java 未创建或显示异常
我正在做一项作业,我必须创建一个时间表,并处理某些输入错误的异常。我让它大部分工作,但对于我的通用异常抛出,它似乎没有创建我想要的对象。我使用重载构造函数来创建它,当我调用消息时,它不会显示我的输入。我的代码如下:Java 未创建或显示异常,java,loops,exception,while-loop,Java,Loops,Exception,While Loop,我正在做一项作业,我必须创建一个时间表,并处理某些输入错误的异常。我让它大部分工作,但对于我的通用异常抛出,它似乎没有创建我想要的对象。我使用重载构造函数来创建它,当我调用消息时,它不会显示我的输入。我的代码如下: import java.util.*; import java.lang.Exception; public class Scheduler{ public static void main() throws Exception{ Scanner input = new S
import java.util.*;
import java.lang.Exception;
public class Scheduler{
public static void main() throws Exception{
Scanner input = new Scanner(System.in);
String name;
int time;
// Program introduction
System.out.println("Welcome to scheduling scheduler 2.0");
System.out.println("You can schedule an appointment at 1, 2, 3, 4, 5, or 6 pm");
// Creating the Array
String[] schedule = new String[6];
// While loop set to
while(filled(schedule) == false){
System.out.print("What is your name? ");
name = input.next();
boolean innerExecute = true;
// Do While loop used in order to loop until a valid time is set instead of asking for
// name again
do{
try{
System.out.print("When do you want to schedule your appointment? ");
time = input.nextInt();
System.out.println();
if(time > 6 || time < 1){
throw new InvalidTimeException("Sorry that is not a valid time");
}
else if(schedule[time - 1] == null){
schedule[time - 1] = name;
innerExecute = false;
}
else if(schedule[time - 1] != null){
throw new TimeInUseException("That time is not available.");
}
else{
throw new Exception("Bad time format, should be an integer.");
}
}
catch(TimeInUseException e){
System.out.println(e.getMessage());
System.out.println();
}
catch(InvalidTimeException e){
System.out.println(e.getMessage());
System.out.println();
}
catch(Exception e){
System.out.println(e.getMessage());
System.out.println();
String voided = input.next();
}
}while(innerExecute == true);
}
System.out.println("The schedule is as follows: ");
System.out.println();
for(int i=0; i<6; i++){
System.out.print("At " + (i+1) + " PM is " + schedule[i]);
System.out.println();
}
}
所有其他异常都正确显示,但此异常打印为空。简单地说,当
nextInt()
找到除int
以外的其他要返回的内容时,它会抛出一个inputmaschException
,而不显示消息。因此getMessage()
返回null
。尝试使用异常#printStackTrace()
来查看堆栈跟踪。当您输入时,
您将得到一个InputMismatchException,您需要首先处理用户的输入,因为用户可能输入任何内容
try {
time = input.nextInt();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Your input should be a number!");
continue;
}
try {
time = input.nextInt();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Your input should be a number!");
continue;
}