aspose file tools*
The moose likes Beginning Java and the fly likes Parse an int from a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Parse an int from a string" Watch "Parse an int from a string" New topic
Author

Parse an int from a string

Mike Oxenfire
Greenhorn

Joined: Jun 08, 2011
Posts: 1
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

Joined: Jul 09, 2010
Posts: 16
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

Joined: Oct 13, 2005
Posts: 36494
    
  16
You can also use the next() and nextInt() methods of Scanner to read the "Shirt" "@" and 2 separately from the input.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36494
    
  16
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

Joined: Oct 13, 2005
Posts: 36494
    
  16
. . . adn welcome to the Ranch
Girish Amara
Greenhorn

Joined: May 28, 2011
Posts: 4

Christopher Nortje is correct. That is the exact reason.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Parse an int from a string
 
Similar Threads
Scanner is skipping
How to let tomcat know my src path?
loading an integer data file into an integer array
string tokenizer, reading from .txt file
Exit this Do-While w/out an int?