• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

Pulling Integer Values from a String  RSS feed

 
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);
}
 
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));
 
Wanderer
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 ]
 
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!