-2

I get NumberFormatException, how do I convert String[] to int[]? The input value I get is of type 'text' for age, I have five input fields for same age input. So im using array to get five age.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {

        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        String[] name=request.getParameterValues("name");
        String[] relation=request.getParameterValues("relation");
        String[] age=request.getParameterValues("age");
        String[] occupation=request.getParameterValues("occupation");
        String[] education=request.getParameterValues("education");

        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sportsevent", "root", "root");

        PreparedStatement ps=con.prepareStatement("insert into multiple(name, relationship, age, occupation, education) values(?,?,?,?,?)");
        for (int i = 0; i < name.length; i++) {
            if(name[i] != null) {
            ps.setString(1, name[i]);
            ps.setString(2, relation[i]);
            ps.setInt(3, age[i]);
            ps.setString(4, occupation[i]);
            ps.setString(5, education[i]);
            }
        }
        ps.executeUpdate();

    }catch (Exception e){System.out.println(e);}
}
cello
  • 5,356
  • 3
  • 23
  • 28
  • Add the stacktrace please. Looks like in some cases the Age is empty, so you have to check it before converting – Jens Mar 22 '17 at 08:10
  • 1
    The code shown above will not throw a NumberFormatException for the simple reason that it won't compile, `age` is `String[]`, so `age[i]` is `String`, and `PreparedStatement#setInt` will not accept `String` as its second parameter. – T.J. Crowder Mar 22 '17 at 08:12
  • 1
    This question is, basically, "How do I parse a number?" – T.J. Crowder Mar 22 '17 at 08:12
  • Possible duplicate of [What is a NumberFormatException and how can I fix it?](http://stackoverflow.com/questions/39849984/what-is-a-numberformatexception-and-how-can-i-fix-it) – xenteros Apr 10 '17 at 09:36

1 Answers1

1

Try in this way;

ps.setInt(3, Integer.parseInt(age[i]));
KOUSIK MANDAL
  • 2,002
  • 1
  • 21
  • 46