2

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.

Adam
  • 355
  • 1
  • 5
  • 12

3 Answers3

8

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()));
Reimeus
  • 152,723
  • 12
  • 195
  • 261
4

It doesn't like the space. Trim the input. Change

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

to

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

It doesn't matter if you use valueOf or parseInt; neither seems to like the trailing space.

rgettman
  • 167,281
  • 27
  • 248
  • 326
0

You should use Integer.parseInt() instead, which should be Integer.parseInt(element).

Seems the space after 5 is causing that. Integer.valueOf(element) should still work without the space.

Cheers.

tmwanik
  • 1,565
  • 13
  • 19