• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

easier way to extract int from string?

 
Imran Bhutta
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a string that a user enters like 1235432 and then i need it to extract the integer values from the string.....



i have that but it only works if there are 9 integers... can anyone help?
 
Ray Stojonic
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thankfully, Java has the ability to loop.

// declare appropriately sized int array

for( int i = 0; i < string.length(); ++i ) {
int n = Integer.parseInt( string.substring( i, i+1 ) );
//store n in array
}
[ October 31, 2004: Message edited by: Ray Stojonic ]
 
Joyce Lee
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Imran,

Alternatively, you can convert the String to int. Then use the % and / to extract the int value as suggested in this thread.

Joyce
[ October 31, 2004: Message edited by: Joyce Lee ]
 
Imran Bhutta
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okk thankx for the loop!, but in an array how would i add the value? beacsue i need to get the total value of the number the user enteres and then i have to see if its % 10 and if it not i have to make it %10.... i konw n+n wont work beacsue its just gonna add n to the same number.
 
Joyce Lee
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Imran,

If you're trying to add up the individual digit of a number, you don't need to store them in an array.

For example:


After getting the sum, you can find the remainder for (sum / 10) by using % operator.



i konw n+n wont work beacsue its just gonna add n to the same number.
Could you show us the code? Maybe we can point out the mistakes (if there's any) for you.

Joyce
[ November 01, 2004: Message edited by: Joyce Lee ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic