2013-03-14 49 views
-2

我需要編寫一個連接數據庫的java程序,程序應該提示用戶輸入7位數的ID,然後計算每個字母等級的出現次數和總數等級。在結果中顯示0無行

例如:學生12345 甲'S:1 乙'S:0 C'S:3 D'S:0 F公司:o TOTAL GRADE:4

我的代碼下面工作正常,但問題是該結果沒有行不給我0前:它只是給我A,C,它刪除了其他人

所以你有任何想法我怎麼能在結果中顯示0。

感謝ü

import java.sql.*; // Use classes in java.sql package 
import java.util.*; 

public class DDBB { 

    public static void main (String args []) { 
     int a; 
     Scanner in = new Scanner(System.in); 
     System.out.println("Enter a 7 digit Number for StudentID"); 
     a = in.nextInt(); 
     System.out.println("StudentID" +" "+ a); 
     int countgrade ; 
     String GRADE1; 
     int totalcount; 
     Connection conn =null; 
     Statement st =null; 
     try { 
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); 
      // Class.forName("oracle.jdbc.driver.OracleDriver"); 
      String url ="jdbc:oracle:thin ...."; 
      conn = DriverManager.getConnection(url,"user", "password"); 
      // create a Statement object 
      PreparedStatement st1 = conn.prepareStatement(
       "SELECT GRADE, Count(*) AS COUNT1 FROM GRADING WHERE StudentID = ? GROUP BY Grade ORDER BY GRADE"); 
      st1.setInt(1, a); 
      ResultSet S = st1.executeQuery(); 
      while (S.next()) { 
       countgrade = S.getInt("COUNT1"); 
       GRADE1 = S.getString("GRADE"); 
       System.out.println(GRADE1 + "'s :"+countgrade+"\n"); 
      } 
      String Q2 ="SELECT COUNT(GRADE) AS COUNT2 FROM GRADING WHERE StudentID = ? "; 
      ResultSet S1 = st1.executeQuery(Q2); 
      while (S1.next()) { 
       totalcount = S1.getInt("COUNT2"); 
       System.out.println("Total grades:"+ " " + totalcount+"\n"); 
      } 
      S.close(); 
     } 
     catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     finally { 
      try { 
       // close the Statement object using the close() method 
       if (st != null) { 
        st.close(); 
       } 
       // close the Connection object using the close() method 
       if (conn != null) { 
        conn.close(); 
       } 
      } 
      catch (SQLException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
+2

這需要一些格式 – 2013-03-14 15:44:56

+0

@MajidLAISSI你現在可以閱讀這個問題嗎? – 2013-03-14 15:50:16

+0

聽起來像是一個家庭作業問題。 – Jeff 2013-03-14 15:50:54

回答

0

好像你應該使用一個for循環,而不是一個while的打印成績(或者只是不使用循環)。

爲什麼不這樣做僞代碼:

int A = B = C = D = F = 0; 
/* Get results as you already are, stored in result set s */ 
while(s.next()) 
{ 
    string grade = s.GetString("GRADE"); 
    if(grade == "A") 
     A = s.GetInt("COUNT1") 
    if(grade == "B") 
     B = s.GetInt("Count1") 
    /*etc*/ 
} 

在while循環結束時,只輸出 「A的:」 + A + 「​​B的:」 ......

當你顯示您的最終成績數,只顯示A + B + C + D + F。

這將其縮減爲一個SQL查詢,並且它將始終顯示每個字母等級。

+0

當然,有可能會收緊的地方。我已經把它作爲練習len了 - 我上面提到的將會起作用,但它可以更好地工作,或者通過一些工作更清晰地閱讀。請享用! – Jeff 2013-03-14 16:00:30