3

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();
        }  
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Sayam Nandy
  • 49
  • 1
  • 1
  • 9
  • 2
    I guess it's time for SO to have a `NumberFormatException` version of [what-is-a-null-pointer-exception-and-how-do-i-fix-it](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Baby Apr 27 '15 at 07:40
  • You have to check all the string which you are converting to int by `Integer.parseInt` to check if the are blank – singhakash Apr 27 '15 at 07:40
  • Looks like `(request.getParameter("pin"));` or `request.getParameter("contact"));` or `request.getParameter("id");` is blank. – Jens Apr 27 '15 at 07:40
  • What numerical value would you put at "" ? – Stultuske Apr 27 '15 at 07:44

5 Answers5

2

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"));
}
TZHX
  • 5,291
  • 15
  • 47
  • 56
Ranjeet
  • 636
  • 6
  • 12
0

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.

JHH
  • 8,567
  • 8
  • 47
  • 91
  • Sir thanks for your help sir.if i do int int id=Integer.parseInt(request.getParameter("id"));...then same thing happens..what should i do??plz advice sir?? – Sayam Nandy Apr 27 '15 at 07:47
  • That code is logically identical with your original code. You are missing the point. The problem is that you are trying to convert a String to an integer, which would work fine if the value of the String was, say, "57", but when the String is empty, you can obviously never convert it to an integer. I mean, what number would you expect an empty string to be converted to? Or what would you expect the result of Integer.parseInt("Unicorns") to be? Obviously it can never be converted to an integer and will throw an exception. – JHH Apr 27 '15 at 07:54
  • What you should do is either make sure that your HTTP request supplies a numerical parameter (currently you don't supply an ID parameter at all), and/or make sure your code can handle a missing parameter gracefully (by catching the exception and make something useful out of it). – JHH Apr 27 '15 at 07:55
  • sir,this is really useful sir..but i'm totally puzzled..i'm sending my update html code..plz fix the servlet code sir.and yes,pin,contact and id will be numeric value... – Sayam Nandy Apr 27 '15 at 08:30
  • Update Conference Record index page
    Search For Update Record
    Confirmation Number    :
    – Sayam Nandy Apr 27 '15 at 08:32
  • this is my html code sir...plz fix the servlet code sir..i really need this..if you want u can send me a mail my mail id--lg_fg2001@yahoo.co.in – Sayam Nandy Apr 27 '15 at 08:34
  • First of all, supply your code propery formatted as part of your question. Second, "please fix my code" isn't the way things work at SO. I try to help people understand programming and solve problems, I don't do their work for them when they don't even make an effort of understanding the problem. – JHH Apr 27 '15 at 09:02
0

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.

GAgarwal
  • 122
  • 4
0

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.

SR_
  • 874
  • 13
  • 31
-1

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.

Jafar Ali
  • 1,084
  • 3
  • 16
  • 39
  • Wow, this is indeed one of the messiest answer I have seen in a while. I would think it makes the OP only more confused. First of all, we established that it's the "id" parameter causing the problem, not the "pin" parameter. Secondly, suggesting four different ways of "safely" parsing an integer, none of which actually takes account for a non-empty, non-numerical string value, is just bad. The preferred way is likely to simply catch the NumberFormatException and do something useful with it in case the string was not parsable into an integer. – JHH Apr 27 '15 at 07:59
  • Bro answer formatted got messed up as i tried ti use bullet as well as code. I took pin as example. and the ans is as generalised as possibe. – Jafar Ali Apr 27 '15 at 08:01
  • Ok fair enough, id or pin, doesn't matter obviously, but I saw a risk of misleading the OP into thinking the problem was with his pin parmeter. Never mind that. The answer does however suggest four different approaches to safely parse a string into an integer, and takes account for null and empty strings, but would crash for strings such as "foo" or "42abc". There's just no benefit of manually trimming, length checking etc, when you could simply catch the exception that handles both empty strings, non-trimmed strings, and non-numerical strings. Sorry to say, but your code is just bad advice. – JHH Apr 27 '15 at 08:04
  • Non trimmed string should be handled since this coudl be from a form field and blank space are a common addition which break code lot of time. I do agree caching exception is one of the soilution but doing is for each and every request parameter will make code repatitive and messy. My Intension for this multiple step answer was to guide him throught code that is less messy per step at the same time he can select the style he is comfortable with. – Jafar Ali Apr 27 '15 at 08:13
  • I understand and appreciate what you are trying to do, but in my opinion your suggestions are unnecessarily messy. Personally I would probably handle trailing whitespace by simply calling trim() and catch Exception rather than NumberFormatException (generally catch-all is a bad practice but in such a controlled case I wouldn't mind letting both NumberFormatException and NullPointException be caught by the same exception handler): try { id = Integer.parseInt(str.trim()); } catch (Exception e) {// id is missing or invalid, do something... }. – JHH Apr 27 '15 at 08:19
  • i don't see why this is messy or unnecessary. If some one is going to control the type of solution to be appeared then this is not an open formum anymore. – Jafar Ali Apr 28 '15 at 06:34