Else part not running inside a while(next()) loop in jsp

时间:2015-07-28 16:03:21

标签: jsp if-statement while-loop

I want to create a table to show if a class occupied or empty in a certain hour of day. The code executes the if part. But when the if condition is not satisfied, else part does not execute either.

            Date d = new Date();
            Calendar c = Calendar.getInstance();
                c.setTime(d);
                int dow = c.get(Calendar.DAY_OF_WEEK);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String today = sdf.format(aja);

                        <td><%
                    String Hours = "07:00:00";
                    String sql1 = ("SELECT * FROM booked_classrooms WHERE block ='"+blockNo+"' AND room_no='"+roomNo+"' AND startTime='"+today+" "+Hours+"';");
                    boolean checkSql1 = false;

                    checkSql1 = st.execute(sql1);

                    if(!checkSql1){%>No Class<% }

                    else{
                        rs = st.executeQuery(sql1);

                    while(rs.next()){
                    Date classStart = sdf1.parse(rs.getString(6));
                      Date routineStartHour = sdf1.parse(today+" "+Hours);


                      c.setTime(classStart);
                    int dow1 = c.get(Calendar.DAY_OF_WEEK);

                       if(dow1 == dow){
                    %>
                    <%=rs.getString(3)%> by <%=rs.getString(2) %><%

                       }else{ %>No Class<%
                       } } 
                     } %></td>

1 个答案:

答案 0 :(得分:0)

清理缩进后,我可以看到问题是你认为循环内else上的if会处理你甚至从未进入循环的情况,它赢了。请参阅下文,了解处理该案例的一种方法。

此外,您可以摆脱浪费处理时间的checkSql1 = st.execute(sql1);。没有必要运行查询两次以查看它是否会运行。

<td><%
String Hours = "07:00:00";
String sql1 = ("SELECT * FROM ....");
String noClassMessage = "No Class"; //making this a variable since its going to be used a few times
boolean blnEnteredLoop = false; //adding boolean to check if we ever enter the loop or not

rs = st.executeQuery(sql1);
while(rs.next())
{
    blnEnteredLoop = true; //setting to true because we're in the loop
    Date classStart = sdf1.parse(rs.getString(6));
    Date routineStartHour = sdf1.parse(today+" "+Hours);
    c.setTime(classStart);
    int dow1 = c.get(Calendar.DAY_OF_WEEK);
    if(dow1 == dow)
    {
        out.print(rs.getString(3)+" by "+rs.getString(2));
    }
    else
    {
        out.print(noClassMessage);
    } 
} 

if(!blnEnteredLoop)
{
    //if we never entered the loop, then print the message
    out.print(noClassMessage);
}
%></td>
相关问题