不知道为什么我得到一个NullPointerException

时间:2017-04-14 13:15:35

标签: java jsp jdbc netbeans ojdbc

我已将数据从数据库输入到数组c_pid[]中。现在我试图运行一个循环。如果数组的值不为null,则循环应该继续。一切似乎都运行良好。我得到了理想的输出。但我遇到的一个问题是,由于某种原因,它显示了我的nullpointer异常。

我提供了代码以及下面的屏幕截图。enter image description here

我正在尝试运行此循环

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);
    }       
%>

2 个答案:

答案 0 :(得分:0)

问题在于循环而不是循环,直到array[index] == nullwhile (!c_pid[cnt].equals(null)) {一样,你必须循环直到数组结束。

<强>推荐

而不是使用:

String[] c_pid = new String[100000];

你可以使用List,它是标准的,你不需要用任何大小的最大数字来初始化它:

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 />");
}

答案 1 :(得分:0)

while (!c_pid[cnt].equals(null))这在这里是邪恶的。将其替换为while(c_pid[cnt]!=null),它应该可以解决问题。