gpt4 book ai didi

java - 如何正确使用try-catch?

转载 作者:行者123 更新时间:2023-12-01 14:09:11 26 4
gpt4 key购买 nike

我正在尝试处理如何使用 try-catch。我知道它会“尝试”主代码,如果它不起作用,它会捕获它并执行不同的东西。我还想不断提示用户输入正确的值。

即使我将 catch 设置为将其包含在其 block 中,我仍然收到输入不匹配异常错误。

澄清一下:当我向用户询问他们计划停留多长时间以及他们想呆在哪一层时,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);


}
}

最佳答案

您现在的 try-catch block 是有缺陷的,因为一旦进入 catch block ,用户所要做的就是输入一些不是整数会使整个程序崩溃。

相反,要获取 stayTime 以及从 Scanner 中提取的所有其他整数,请创建一个单独的函数,该函数会阻塞,直到用户输入一个整数:

private static int parseIntFromScanner(Scanner sc) {
while(true) {
try {
int toReturn = sc.nextInt();
return toReturn;
} catch(InputMismatchException ime) {
//Continue back to the top of the loop, ask again for the integer
}
}
}

关于java - 如何正确使用try-catch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18670579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com