Exception Occured java.lang.NumberFormatException:null

时间:2016-09-29 10:14:46

标签: java null numberformatexception

我在JSP页面中收到以下错误

SELECT * FROM books WHERE id =1001
Exception Occuredjava.lang.NumberFormatException: null

在代码下运行时。 我怀疑这是由于

input type='text' size='3' value='1' name='qty'<%=id%中的{p> JSearch.jsp未正确关联 JOrder.jsp中的int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id));。 任何人都可以帮助我。

代码:JSearch.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %> 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Search Page</title>
    </head>
    <body>
         <% try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@//XXXXX.XXX:1521/xe", "sai", "harisai");
            Statement stmt=conn.createStatement();
            // Retrieve and process request parameters: "author" and "search"
            String author = request.getParameter("author");
            boolean hasAuthorParam = author != null && !author.equals("Select...");
            String searchWord = request.getParameter("search");
            boolean hasSearchParam = searchWord != null && ((searchWord = searchWord.trim()).length() > 0);%>
            <h2>Query Results</h2>
            <%if (!hasAuthorParam && !hasSearchParam) { %> <%--No params present--%>
              <h3>Please select an author or enter a search term!</h3>
              <p><a href='Entryscreen.jsp'>Back to Select Menu</a></p>
              <% } 
             else {
             // Form a SQL command based on the param(s) present
            StringBuilder sqlStr = new StringBuilder();  // more efficient than String
            sqlStr.append("SELECT * FROM books WHERE qty > 0 AND (");
            if (hasAuthorParam) {
               sqlStr.append("author = '").append(author).append("'");
            }
            if (hasSearchParam) {
               if (hasAuthorParam) {
                  sqlStr.append(" OR ");
               }
               sqlStr.append("author LIKE '%").append(searchWord)
                     .append("%' OR title LIKE '%").append(searchWord).append("%'");
               sqlStr.append(") ORDER BY author, title");
             }//
            out.println(sqlStr);  // for debugging
            ResultSet rset = stmt.executeQuery(sqlStr.toString());
            if (!rset.next()) { %> <%--// Check for empty ResultSet (no book found)--%>
               <h3>No book found. Please try again!</h3>
               <p><a href='start'>Back to Select Menu</a></p>
               <%} 
            else {%>
               <%--// Print the result in an HTML form inside a table--%>
               <form method='get' action='JOrder.jsp'>
               <table border='1' cellpadding='6'>
                <tr>
               <th>&nbsp;</th>
               <th>AUTHOR</th>
               <th>TITLE</th>
               <th>PRICE</th>
               <th>QTY</th>
               </tr>
               <%-- // ResultSet's cursor now pointing at first row--%>
               <% do {
                  // Print each row with a checkbox identified by book's id
                  String id = rset.getString("id");%>
                  <tr>
                  <td><input type='checkbox' name='id' value='<%=id%>' /></td>
                  <td><%=rset.getString("author")%></td>
                  <td><%=rset.getString("title")%></td>
                  <td>$<%=rset.getString("price")%></td>
                  <td><input type='text' size='3' value='1' name='qty'<%=id%>/></td>
                  </tr>
               <%} while (rset.next()); %> 
               </table><br/>
                <%--// Ask for name, email and phone using text fields (arranged in a table)--%>
               <table>
              <tr><td>Enter your Name:</td>
              <td><input type='text' name='cust_name'/></td></tr>
               <tr><td>Enter your Email (user@host):</td>
               <td><input type='text' name='cust_email' /></td></tr>
               <tr><td>Enter your Phone Number (8-digit):</td>
               <td><input type='text' name='cust_phone' /></td></tr></table><br />
               <%-- // Submit and reset buttons--%>
               <input type='submit' value='ORDER' />
               <input type='reset' value='CLEAR' /></form>
              <% 
               }
            }
        }
        catch (Exception e){
        out.println("Exception Occured:" +e);
        } %>
      </body>
</html>

代码: JOrder.jsp

     <%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %> 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Order Confirmation</title>
    </head>
    <body>
        <h1>Order Confirmation</h1>
        <% try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@//XXXXX.XXX.LOCAL:1521/xe", "sai", "harisai");
            Statement stmt=conn.createStatement();
            // Retrieve and process request parameters: id(s), cust_name, cust_email, cust_phone
            String[] ids = request.getParameterValues("id");  // Possibly more than one values
            String custName = request.getParameter("cust_name");
            boolean hasCustName = custName != null && ((custName = custName.trim()).length() > 0);
            String custEmail = request.getParameter("cust_email").trim();
            boolean hasCustEmail = custEmail != null && ((custEmail = custEmail.trim()).length() > 0);
            String custPhone = request.getParameter("cust_phone").trim();
            boolean hasCustPhone = custPhone != null && ((custPhone = custPhone.trim()).length() > 0);
             // Validate inputs
            if (ids == null || ids.length == 0) {%>
            <h3>Please Select a Book!</h3>
            <% } else if (!hasCustName) {%>
            <h3>Please Enter Your Name!</h3>
           <% } else if (!hasCustEmail || (custEmail.indexOf('@') == -1)) {%>
            <h3>Please Enter Your e-mail (user@host)!</h3>
            <%} else if (!hasCustPhone || (custPhone.length() != 8)) {%>
            <h3>Please Enter an 8-digit Phone Number!</h3>
            <%} else {%>
            <%--// Display the name, email and phone (arranged in a table)--%>
            <table>
            <tr><td>Customer Name:</td><td><%=custName%></td></tr>
            <tr><td>Customer Email:</td><td><%=custEmail%></td></tr>
            <tr><td>Customer Phone Number:</td><td><%=custPhone%></td></tr></table>
            <%--// Print the book(s) ordered in a table--%>
            <br/>
            <table border='1' cellpadding='6'>
            <tr><th>AUTHOR</th><th>TITLE</th><th>PRICE</th><th>QTY</th></tr>
            <%  float totalPrice = 0f;
                for(String id : ids) {             
                String sqlStr = "SELECT * FROM books WHERE id ="+ id;
                out.println(sqlStr);
                // for debugging
                ResultSet rset = stmt.executeQuery(sqlStr);
                rset.next();
               int qtyAvailable = rset.getInt("qty");
               String title = rset.getString("title");
               String author = rset.getString("author");
               float price = rset.getFloat("price");
               int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id));
               sqlStr = "UPDATE books SET qty = qty -"+ qtyOrdered +" WHERE id =" + id;
               out.println(sqlStr);  // for debugging
               stmt.executeUpdate(sqlStr);
               sqlStr = "INSERT INTO ORDER_RECORDS VALUES ("+ id + ", " + qtyOrdered + ", '" + custName + "', '"
                       + custEmail + "', '" + custPhone + "')";
               out.println(sqlStr);  // for debugging
               stmt.executeUpdate(sqlStr);%>        
               <%-- // Display this book ordered--%>
               <tr>
               <td><%=author%></td>
               <td><%=title%></td>
               <td><%=price%></td>
               <td><%=qtyOrdered%></td></tr>
               <% totalPrice += price * qtyOrdered;
            }%>
            <tr><td colspan='4' align='right'>Total Price: $
             </td> <%out.println(totalPrice);%> </tr>
            </table>
            <h3>Thank you.</h3>
            <%out.println("<p><a href='JEntryScreen.jsp'>Back to Select Menu</a></p>");
         }
       }
        catch (Exception e) {
            out.println("Exception Occured" +e);
            }
        finally {     
            }%>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

什么是NumberFormatException

  

抛出以指示应用程序已尝试将字符串转换为其中一种数字类型,但该字符串没有适当的格式。

- [文档] [2]

NumberFormatException extends IllegalArgumentException。它告诉我们它更专业IllegalArgumentException。实际上,它用于突出显示虽然参数类型是正确的(StringString的内容不是数字( a,b,c, d,e,f在HEX中被视为数字,在需要时是合法的)。

<强> Ad. 2.

当你看到,而不是"For input string:"和输入时,有一个null不是"null" ),这意味着你试图通过对数字的null引用。如果您真的想要处理为0或任何其他数字,您可能会对我在StackOverflow上的另一篇文章感兴趣。它可以[这里] [3]。

主题 [什么是NullPointerException以及如何修复它?] [4] 中描述了解决意外null的问题。

答案取自this主题 - 我无法将其标记为副本,因为我在编辑问题之前已经提出了另一个标记。