如何从循环中返回一个值?

时间:2014-12-20 07:36:00

标签: java loops return-value

我创建了一个方法,它由一个在另一个内部的许多循环组成。我想从这个方法返回一个值,它在for循环中初始化。我可以返回这个吗?

  public static String check_payment_status(String id){
    String remaining_amount;
    try {
        ResultSet courseid=dbcon().executeQuery("select course_id from student where student_id='"+id+"'");

        while(courseid.next()){
          String idcrs=courseid.getString("course_id");
          ResultSet rsfee=dbcon().executeQuery("select fee from course where course_id='"+idcrs+"'");

          while(rsfee.next()){
            int fee=rsfee.getInt("fee");
            ResultSet payments=dbcon().executeQuery("select amount from payment where student_id='"+id+"'");
            int pmnt[]=new int[30];
            int add=0;
            for(int i=0;payments.next();i++){
                pmnt[i]=payments.getInt("amount");
                add+=pmnt[i];
            }
            int rem_amout_pay=   fee-add;
            remaining_amount= Integer.toString(rem_amout_pay);
         }
      }
    } catch (Exception e) {
    }
    return remaining_amount;    
}

1 个答案:

答案 0 :(得分:0)

一旦计算了返回值,你想离开循环,你可以通过将return语句放在循环中来实现:

public static String check_payment_status(String id)
{
    String remaining_amount = null;
    try {
        ResultSet courseid=dbcon().executeQuery("select course_id from student where student_id='"+id+"'");   
        while(courseid.next()){
            String idcrs=courseid.getString("course_id");
            ResultSet rsfee=dbcon().executeQuery("select fee from course where course_id='"+idcrs+"'");    
            while(rsfee.next()){
                int fee=rsfee.getInt("fee");
                ResultSet payments=dbcon().executeQuery("select amount from payment where student_id='"+id+"'");
                int pmnt[]=new int[30];
                int add=0;
                for(int i=0;payments.next();i++){
                    pmnt[i]=payments.getInt("amount");        
                    add+=pmnt[i];        
                }
                int rem_amout_pay = fee - add;
                return Integer.toString(rem_amout_pay);    
            }                
        }
    } catch (Exception e) {
    } 
    return remaining_amount;
}

请注意,如果未在循环内部返回语句,则仍需要在方法结束时使用return语句。