How to debug “java.lang.NumberFormatException: For input string: X” in Java?

被刻印的时光 ゝ 提交于 2021-02-05 06:22:07

问题


I am trying to run one program. I am really very new on Java. When I run my program I am getting following exception:

Description: The server encountered an internal error () that prevented it from fulfilling this request.

Exception: java.lang.NumberFormatException: For input string: ""
    java.lang.NumberFormatException.forInputString(Unknown Source)
    java.lang.Integer.parseInt(Unknown Source)
    java.lang.Integer.parseInt(Unknown Source)
    UpdateSearchRecord.doPost(UpdateSearchRecord.java:56)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717

Here is my code for your reference:

import java.io.IOException;`
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
//import java.sql.ResultSet;
//import java.sql.ResultSetMetaData;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UpdateSearchRecord
 */
public class UpdateSearchRecord extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateSearchRecord() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        String confo = request.getParameter("confo");
        String name = request.getParameter("name");
        String program = request.getParameter("program");
        String country = request.getParameter("country");
        String city = request.getParameter("city");
        String state = request.getParameter("state");
        int pin = Integer.parseInt(request.getParameter("pin"));
        int contact = Integer.parseInt(request.getParameter("contact"));
        String address = request.getParameter("address");
        String idd = request.getParameter("id");
        int id = Integer.parseInt(idd);

        int confor = 0;


        if(uname.equals("") 
            || pwd.equals("") 
            || confo.equals("") 
            || name.equals("") 
            || program.equals("") 
            || country.equals("") 
            || city.equals("") 
            || state.equals("") 
            || address.equals("")){

            out.println("Please insert valid data");
            out.println("<input type=\"text\" value=\"confo\" " + "name=\"confor\">");
            RequestDispatcher rd = request.getRequestDispatcher("UpdateRecord");
            rd.forward(request, response);

        } else {
            confor=Integer.parseInt(confo);
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
                Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sayam");

                PreparedStatement ps=con.prepareStatement(
"UPDATE SP SET uname=?,pwd=?, confo=?,name=?,program=?, country=?,city=?,state=?,pin=?,contact=?,address=? where id=? ");

                ps.setInt(12,id);
                ps.setString(1,uname); 
                ps.setString(2,pwd);
                ps.setInt(3,confor);
                ps.setString(4,name);
                ps.setString(5,program);
                ps.setString(6,country);
                ps.setString(7,city);
                ps.setString(8,state);
                ps.setInt(9,pin);
                ps.setInt(10,contact);
                ps.setString(11,address);
                //ps.setInt(12,id);

                int i=ps.executeUpdate();
                if(i > 0) {
                    out.print("Record successfully Updated");
                }
            } catch (Exception e) {
                System.out.println(e);
            }
            out.close();
        }  
    }
}

回答1:


You need to check whether string is not empty before using parseInt() function. e.g.

if(request.getParameter("pin")!=null && !request.getParameter("pin").equals("")){
    int pin=Integer.parseInt(request.getParameter("pin"));
}



回答2:


In your program four times you are using Integer.parseInt(), so before parsing the string to integer so have to check that all values should be numeric and no alphabets will be there. For that you can use the regular expressions.




回答3:


If you intend to write a server application you should make it resilient to malformed requests.

The error is near line 56 of your code :

int id=Integer.parseInt(idd);

According to the exception, idd is an empty string.

You should check for the existence of the parameters, and then the correctness of their contents. By correctness of their contents, I mean that you should check what is contained in the parameter, independently from other consideration, particularly independently from your business logic.

An integer must not be "wrong123int". An integer must not be sent as an empty string "" if it is mandatory.

There are numerous frameworks dedicated to ease the programming of web applications in order to let you focus on your business.

If you don't want to have a look right now because you're new to Java, you may just test your String parameters for nullity, then for type correctness, then for consistency. I suggest that you create an helper class dedicated to the decoding of parameters.

For your code you could do something like :

boolean mandatoryIdIsCorrect = false;
if (null != idd)
{
  try
  {
    id = Integer.parseInt(idd);
    if (id > 0)
      mandatoryIdIsCorrect = true;
  }
  catch (NumberFormatException e)
  {
  }
}
if (!mandatoryIdIsCorrect)
{
  // Treat the case 
}

but I strongly suggest that you look for a framework to ease your work.




回答4:


This line

int id=Integer.parseInt(idd);

is throwing a NumberFormatException because it's trying to convert a String to an int, but the String does not contain a numerical value. The value comes from

String idd=request.getParameter("id");

But with the current amount of info I have no way of knowing what you expected the "id" parameter to be set to when running, but the stack trace does reveal that the value it in fact found when trying to parse for an int was an empty string ("").

So how did I find this? Well, you have a stack trace saying that the exception was caused by

UpdateSearchRecord.doPost(UpdateSearchRecord.java:56)

If you go to line 56, this is where you call Integer.parseInt.

You should probably add a

try {
    id = Integer.parseInt(idd);
}
catch (NumberFormatException e) { 
    // Do something useful in case there is no "id" parameter, 
    // whether that is assigning id a default value of zero,
    // failing the request, or whatever suits your needs.
}

Whether or not the request can still be fulfilled without a proper id parameter I don't know since I don't know your use case, it could very well be that you'd want the request to fail if the parameter is missing.




回答5:


You are getting blank string from request parameter. I assume you really need those variable as Int.

I am taking pin as an example.

Then Do this

int pin=Integer.parseInt((request.getParameter("pin")==null || request.getParameter("pin").trim().equals(""))?"0":request.getParameter("pin"));

If you feel this is messy then you can do

String pinStr = request.getParameter("pin");
int pin=Integer.parseInt(pinStr==null || pinStr.trim().lenght()==0)?"0":pinStr);

If you feel evan this is messy then

int pin = 0;
String pinStr = request.getParameter("pin");
if(pinStr!=null && pinStr.trim().lenght()>0){
    Integer.parseInt(pinStr);
}

and the simplets and reusable,

Create a reusable utility method

public static int parsIntSafe(String intStr){
    if(intStr!=null && intStr.trim().lenght()>0){
        return Integer.parseInt(intStr);
    }
    return 0;
}

and use this in your code

String pinStr = xyzClass.parsIntSafe(request.getParameter("pin"));

I hope this was helpfull.



来源:https://stackoverflow.com/questions/29889821/how-to-debug-java-lang-numberformatexception-for-input-string-x-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!