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

标签 java for-loop exception try-catch

我正在尝试处理如何使用 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/

相关文章:

java - 解决 JBoss 中的 session 固定问题

将复选框值保存到数组(本地存储)的 JavaScript 在 for 循环期间重复自身

android - 将页脚添加到 ListView 引发 "cannot be cast to android.widget.HeaderViewListAdapter"

spring - bean 名称 'login' 的 BindingResult 和普通目标对象都不能用作请求属性

c++ - 反对异常(exception)

java - 如何在 ListView 中对电话联系人进行排序?

java - Eclipse 类突然找不到

java - jar 不会显示图像

c - 如何在模拟 24 小时之前或之时停止执行的模拟程序

java - 重构 - 简化 java 中的嵌套 for 循环