2017-04-14 109 views
0

我已經從數據庫輸入數據到數組c_pid[]。現在我試圖運行一個循環。如果數組的值不爲null,則循環應該繼續。一切似乎運行良好。我正在獲得所需的輸出。但我遇到的一個問題是,由於某種原因,它向我展示了空指針異常。不知道爲什麼我得到一個NullPointerException

我已經提供了代碼以及下面的截圖。 enter image description here

我試圖像你這樣while (!c_pid[cnt].equals(null)) {你要運行這個循環

while(!c_pid[cnt].equals(null)){ 

後即時得到java.lang.NullPointerException錯誤

<%@page import="storage.data"%> 
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 
<% 
    String[] c_pid = new String[100000]; 
    String c = "", pna = "", pty = "", ppr = "", stock = "", imgpath = ""; 
    //String myList = new String[10]; 
    int a = 0, d = 0; 
    int result = 0, count = 0; 
    int setres; 
    int[] arr = new int[100000]; 
    String testval = "75"; 
    int item_id = 0; 
    data dt = new data(); 
    String item = "", cartid = "", user = ""; 
    String[] prdid = new String[60]; 
    int cnt = 0; 

    try { 
     dt.st = dt.cn.createStatement(); 
     String select_match = "SELECT user_prod_id, COUNT(*) AS rep " 
       + "FROM cart_table " 
       + "GROUP BY user_prod_id " 
       + "ORDER BY rep desc"; 
     dt.rs = dt.st.executeQuery(select_match); 

     while (dt.rs.next()) { 
      //prdid[a] = dt.rs.getString("user_prod_id"); 
      //a=a+1; 
      c_pid[cnt] = dt.rs.getString("user_prod_id"); 
      cnt = cnt + 1; 
     } 
     out.println("<br/>---------xxx--------"); 
     String select3 = "select " 
       + "product_table.p_id,product_table.p_type," 
       + "product_type.pt_id," 
       + "product_table.p_name,product_table.imgpath,product_table.p_price,product_table.stock,product_table.add_date," 
       + "product_type.pt_name " 
       + "from product_table " 
       + "inner join product_type " 
       + "on product_table.p_type=product_type.pt_id " 
       + "order by product_table.add_date desc" 
       + ""; 
     cnt = 0; 
     int size = c_pid.length; 
     out.println("Size of array is " + size + "<br />"); 
     while (!c_pid[cnt].equals(null)) { 
      out.println(c_pid[cnt] + "<br />"); 

      cnt = cnt + 1; 
     } 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
     out.println(ex); 
    }  
%> 
+0

當您收到空指針異常時,還會獲得發生這種情況的信息。 – tilz0R

+1

你不能比較這樣的空!c_pid [cnt] .equals(null)。,你應該比較像(c_pid [cnt]!= null)希望這有助於。 –

+0

@PorkkoM由於它工作!感謝上帝 –

回答

0

的問題是在循環,而不是循環,直到array[index] == null循環直到數組結束。

推薦

而不是使用:

String[] c_pid = new String[100000]; 

您可以使用列表,相反,它是標準的,你不需要用最大數量初始化它是開放的任何大小:

List<String> c_pid = new ArrayList<>(); 
... 
c_pid.add(dt.rs.getString("user_prod_id")); 
... 
out.println("Size of array is " + c_pid.size() + "<br />"); 
.... 
out.println("Size of array is " + c_pid.size() + "<br />"); 
for (String str : c_pid) { 
    out.println(str + "<br />"); 
} 
0

while (!c_pid[cnt].equals(null))這是一個邪惡在這裏。用while(c_pid[cnt]!=null)代替它,它應該可以解決這個問題。

相關問題