This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Pulling Integer Values from a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Pulling Integer Values from a String" Watch "Pulling Integer Values from a String" New topic
Author

Pulling Integer Values from a String

Phil Lewis
Greenhorn

Joined: Apr 01, 2003
Posts: 4
I am trying to create a program which gets all the odd numbers from a barcode (Which is a String), and adds them together.
I have tried the code below, but instead of adding the integer values, it adds the ASCII values.
What is the easiest/best way of pulling the integers out of the String?
Many thanks

public static void main (String [] args)
{
String barcode = "1234567891234";
int number, theNumber, value=0;

for (number=0; number<12; number=number+2){
theNumber=barcode.charAt(number);
value=value+theNumber;

System.out.println("The Value is " +value);
}
Saurav Chetia
Greenhorn

Joined: Oct 28, 2002
Posts: 10

The problem is in this line of code -
"theNumber=barcode.charAt(number); "
You'll get a character literal from the string and then you are assigning that to an integer.
So the integer value of that ASCII char is assigned.
You can try this to obtain the integer value from the String 'barcode'-
theNumber=Integer.parseInt(barcode.substring(number,number+1));
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Another simple (and faster) way to convert a unicode digit into an integer (works for chars '0'-'9' only):
int value = barcode.charAt(number) - '0';
[ April 05, 2003: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451

int value = barcode.charAt(number) - '0';

That somehow reminds me of C


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
 
Don't get me started about those stupid light bulbs.
 
subject: Pulling Integer Values from a String
 
Similar Threads
Finding a prime factor
Integer values (Not ASCII) from within a String
Help needed!
100 == 100 but 1000 != 1000 - what's going on? [boxing, ==, and equals()]
number to text convertion