Search code examples
javastringintegernumberformatexception

How to convert from string to integer? Keep getting NumberFormatException using valueOf();


I'm trying to convert a string to an Integer (not primitive int) before I store it in a Stack<Integer>, but I keep getting a NumberFormatException if I use this syntax:

String element = "5 ";
System.out.println(Integer.valueOf(element));

Could someone explain how to use valueOf(); correctly?

edit: I've tried parseInt(); which gives the same exception, and I want it in an Integer, not int, anyway.


Solution

  • Integer.valueOf will balk on any non-numeric characters. Either remove the trailing space manually or call String#trim():

    String element = "5 ";
    System.out.println(Integer.valueOf(element.trim()));