2017-04-14 117 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)代替它,它应该可以解决这个问题。

相关问题