簡體   English   中英

發生的異常java.lang.NumberFormatException:null

[英]Exception Occured java.lang.NumberFormatException: null

我在JSP頁面中收到以下錯誤

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

在以下代碼下運行。 我懷疑這是由於

input type='text' size='3' value='1' name='qty'<%=id%JSearch.jsp中未正確鏈接到int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id)); 在JOrder.jsp中。 誰能幫我這個忙。

代碼: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>

什么是NumberFormatException

引發以指示應用程序已嘗試將字符串轉換為數字類型之一,但是該字符串沒有適當的格式。

-[文檔] [2]

NumberFormatException extends IllegalArgumentException 它告訴我們它是更專業的IllegalArgumentException 確實,它用於突出顯示,盡管參數類型是正確的( String ),但String的內容不是數字( a,b,c,d,e,f被認為是HEX中的數字,在需要時是合法的 )。

廣告。 2。

當您看到時,它不是"For input string:"和輸入,而是一個null不是"null" ),這意味着您試圖將空值引用傳遞給數字。 如果您實際上想將其視為0或任何其他數字,則可能對我在StackOverflow上的另一篇文章感興趣。 [在這里] [3]可用。

在主題[什么是NullPointerException以及如何解決它?] [4]中對解決意外的null的描述進行了很好的描述。

答案來自主題-我無法將其標記為重復項,因為在問題被編輯之前我提出了另一個標志。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM