我正在尝试处理如何使用 try-catch。我知道它会“尝试”主代码,如果它不起作用,它会捕获它并执行一些不同的东西。我还想继续提示用户输入正确的值。
我不断收到 inputmismatch 异常错误,即使我将 catch 设置为在其块中。
澄清一下:当我向用户询问他们计划停留多长时间以及他们想在哪个楼层时,try-catch 将在那里。因此,我想处理的错误涉及非整数,如果它们超出了“酒店”的范围。
这是我的代码:
public class Hotel{
public static void main(String[] args) throws IOException {
int choice = 0;
String guestName = " ";
int stayTime = 0;
int floorPref = 0;
System.out.println("Welcome to the Hotel California.");
Scanner sc = new Scanner(System.in);
Room[][] hotel = new Room[8][20];
for(int i = 0; i< hotel.length; i++){
for(int j = 0; j<hotel[i].length;j++){
hotel[i][j] = new Room(0,false,"none",0.00,0);
int roomNum = ((i+1) * 100) + (j + 1);
hotel[i][j].setRoom(roomNum);
int roomCheck = hotel[i][j].getRoomNumber();
if(roomCheck > 500){
hotel[i][j].setPrice(350.00);
}
else if(roomCheck < 500){
hotel[i][j].setPrice(200.00);
}
}
}
// Guest check-in interface.
do{
System.out.println("What business have you today?");
System.out.println("1. Guest Registration");
System.out.println("2. Guest Checkout");
System.out.println("3. Show me occupied rooms");
System.out.println("4. Exit");
choice = sc.nextInt();
if(choice == 1){
System.out.println("Tell us about yourself.");
System.out.println("Please input your name:");
guestName = sc.next();
System.out.print("How long are you planning to stay?");
try{
stayTime = sc.nextInt();
}
catch(InputMismatchException e){
System.out.println("Please input a valid integer.");
stayTime = sc.nextInt();
}
System.out.println("Great. What floor would you like to be on? Enter a number 1-8, 0 for no preference.");
floorPref = sc.nextInt();
System.out.println("The following rooms are available based on your floor preference (floors 1-8, 0 for no preference: ");
}
if(floorPref > 0){
for(int i = 0; i < hotel[floorPref].length; i++){
if(hotel[floorPref][(i)].getOccupation() == false){
System.out.print("Rooms " + hotel[floorPref-1][i].getRoomNumber() + ", ");
}
}
System.out.println("Are available today.");
}
else if(floorPref == 0){
for(int i = 0; i < hotel.length; i++){
for(int j = 0; j < hotel[i].length; j++){
System.out.print("Room " + hotel[i][j].getRoomNumber() + ", ");
}
}
System.out.println("Is available.");
}
}while(choice != 4);
}
}