File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Pulling Integer Values from a String" Watch "Pulling Integer Values from a String" New topic

Pulling Integer Values from a String

Phil Lewis

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){

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

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'-
Jim Yingst

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
I agree. Here's the link:
subject: Pulling Integer Values from a String
It's not a secret anymore!