How to debug "java.lang.NumberFormatException: for input line: X" in Java?

I am trying to run one program. I am really very new to Java. When I run my program, I get the 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();
        }  
    }
}

      

+3


source to share


5 answers


Before using the function, parseInt()

you need to check if the string is not empty. eg



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

      

+1


source


This line

int id=Integer.parseInt(idd);

      

throws a NumberFormatException because it is trying to convert a String to an int, but the String does not contain a numeric value. The meaning comes from

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

      

But with the current amount of information, I don't know what you expected from the "id" parameter to be set at startup, but the stack trace shows that the value it actually found when trying to parse an int was an empty string ("").

So how did I find this? Well you have a stack trace saying that an exception was thrown



UpdateSearchRecord.doPost(UpdateSearchRecord.java:56)

      

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

You should probably add

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.
}

      

Is it possible to execute the request yet without the correct id parameter, which I don't know, since I don't know your use case, it is entirely possible that you want the request to fail if the parameter is missing.

0


source


In the program, you use Integer.parseInt () four times, so before parsing the string as a whole, it should check that all values ​​must be numeric and not alphabets. You can use regular expressions for this.

0


source


If you are going to write a server application, you must make it robust against 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 have to check for the parameters and then their content is correct. By the correctness of their content, I mean that you should validate what is contained in the parameter regardless of other consideration, especially regardless of your business logic.

The whole number should not be "wrong123int"

. The integer should not be sent as an empty string ""

if needed.

There are many frameworks designed to make it easier to program web applications so you can focus on your business.

If you don't want to look right now because you are new to Java, you can simply check your String parameters for nullity, then for type correctness, and then for consistency. I propose to create a helper class dedicated to parameter decoding.

For your code, you can 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 highly recommend that you look for a structure that makes your job easier.

0


source


You get an empty string from the request parameter. I assume you really need these variables as Int.

I am using 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 like it's a mess, you can do

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

      

If you feel evan it's dirty and then

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

      

and simple and reusable,

Create a reusable 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 helpful.

-1


source







All Articles