Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pulling Integer Values from a String

 
Phil Lewis
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

That somehow reminds me of C
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic