有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

try-catch方法中的java返回值

 public double calRoomCharges(int cusId)


{

    try
    {


        //Get Rates
        String sql="SELECT nights FROM reservation where cus_id ='"+cusId+"'";
        pst=conn.prepareStatement(sql);
        rs=pst.executeQuery();
        int roomRates = 0;
            if(!rs.next())
            {
                //handle no result
            } 
            else 
            {
                roomRates = rs.getInt("nights") ;

            }
            double tot1 =roomRates;
            String totRoom = String.valueOf(tot1);
            rc.setText(totRoom);

    }
    catch(Exception e){}




 }

我想从这个方法中得到更多的空间。我该怎么退呢?如果我把return语句放在try-catch块之外,它就不会接受块内计算的值


共 (1) 个答案

  1. # 1 楼答案

    你可以试试这样的。让我知道这是否有效

    public double calRoomCharges(int cusId)
    {
        String totRoom = "";
        double totalCharge = 0.0;
    
        try
        {
            //Get Rates
            String sql="SELECT nights FROM reservation where cus_id ='"+cusId+"'";
            pst=conn.prepareStatement(sql);
            rs=pst.executeQuery();
            int roomRates = 0;
                if(!rs.next())
                {
                    //handle no result
                } 
                else 
                {
                    roomRates = rs.getInt("nights") ;
                    totalCharge = roomRates; // calculate total charge
                    String totRoom = String.valueOf(totalCharge);
                    rc.setText(totRoom);
    
                }
    
        }
        catch(Exception e){
            System.out.prtintln(e.getMessage());
        }
    
        return totalCharge;
     }