繁体   English   中英

如何正确使用try-catch?

[英]How to properly use try-catch?

我正在尝试处理如何使用try-catch。 我知道它将“尝试”主代码,如果不起作用,它将捕获并执行其他操作。 我还要继续提示用户输入正确的值。

即使我将catch设置为在其代码块中,我仍会收到inputmismatch异常错误。

需要澄清的是:当我要求用户提供关于他们打算停留多长时间以及他们希望停留在多大楼层上的信息时,就会尝试尝试。 因此,我要处理的错误涉及非集成商,如果它们不在“酒店”范围之内。

这是我的代码:

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块存在缺陷,因为一旦进入catch块,用户所需要做的就是输入非整数的值来使整个程序崩溃。

相反,要获取stayTime和您从Scanner提取的所有其他int,请创建一个单独的函数,该函数将阻塞直到用户输入int为止:

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
        }
    }
}

尝试将其放在代码的顶部

import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;

并且在您的public static void throws IOException main删除中throws IOException因此它仅保留public static void main希望它将起作用

以下是一小段要分割的代码。如果用户输入零,它将捕获,您也可以输入数字。 请注意,该代码仅会捕获一次。我使用了不推荐使用的方法,这仅是您需要的一个示例。

import java.io.DataInputStream;
import java.io.IOException;


public class test1 {
    public static void main(String args[]) throws NumberFormatException, IOException
    {
        DataInputStream d=new DataInputStream(System.in);int x;
        try {
             x=Integer.parseInt(d.readLine());
            int z=8;
            System.out.println(z/x);
        } catch (Exception e)
        {
            System.out.println("can not divide by zero");
            x=Integer.parseInt(d.readLine());
        }
    }

}

为了回答您为什么仍然失败的问题:对nextInt()所有调用都可能引发InputMistmatchException ,不仅是try-catch块的try部分中的内容。 这就是现在正在发生的事情。

另一个问题是在catch块内第二次调用nextInt 在catch块中引发的异常需要它们自己的处理,与它们所属的try-catch块分开。 因此,如果catch块内的nextInt抛出InputMismatchException ,它将离开try-catch块并从那里继续前进。 对于已发布的代码,这意味着main将在异常时终止。

一点,正如musical_coder指出的那样,代码需要与验证一起循环。 否则,如果第二次读取值的尝试失败,它将最终没有设置值。

顺便说一句,请参见: 重做Java后的尝试 ,以获取有关使用扫描仪的提示,这将导致更多的麻烦。 实际上,它说明了为什么现在使用try-catch进行处理总是会最终终止程序。 (这取决于扫描仪的功能)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM