File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Parse an int from a string

 
Mike Oxenfire
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been trying to get an integer from a scanned string and can't seem to get it to work. Here's my code:


The idea is to enter an item @ quantity e.g "Shirt @ 2" and put shirt into one ArrayList and qty into another.
qty holds Integers.
Here's the exception I get, it's thrown at the last line of shown code:

Exception in thread "main" java.lang.NumberFormatException: For input string: "shirt "
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)

Thanks in advance.
 
Christopher Nortje
Greenhorn
Posts: 16
  • 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the input is "Shirt @ 2" and you split using "@" you would have an array like this:
qty1[0] ="Shirt ";
qty1[1] =" 2";
You need to access the second value at the second index instead of the first:
Example
qty1[1]
Remember to trim() your String as your numeric value contains a space.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47295
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also use the next() and nextInt() methods of Scanner to read the "Shirt" "@" and 2 separately from the input.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47295
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also change the delimiter on your Scanner to include whitespace and the at sign @. Beware of the nextLine() method after a nextXXX() method; there is a risk of it returning an empty line.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47295
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . adn welcome to the Ranch
 
Girish Amara
Greenhorn
Posts: 4
Eclipse IDE Java Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christopher Nortje is correct. That is the exact reason.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic