Win a copy of Head First Android this week in the Android forum!
  • 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Position of Numbers?

 
Ranch Hand
Posts: 36
Eclipse IDE Chrome Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey guys.

if I had a variable of type int and I wanted to split it into one digit numbers, how would I do this?

 
Ranch Hand
Posts: 441
Scala IntelliJ IDE Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use / and % (modulus) operators

e.g. to get the "hundreds" digit of int a = 1234567

int n = a / 100 % 10

Alternatively if you want it as characters, use String.valueOf(a).toCharArray()
 
lowercase baba
Posts: 13013
66
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
do you know the length/magnitude of the number ahead of time? if not, you'll probably be better using an array or arrayList rather than hard-coding 'split1', 'split2', etc.
 
Marshal
Posts: 74359
334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Luigi Plinge wrote: . . . int n = a / 100 % 10 . . .

Are you sure about that? Have you got the / and the % in the right places?
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It helps,

int i = 987654320;
int j=1;
while(j>0){
j=i/10;
System.out.println(i%10);
i=j;
}
 
Luigi Plinge
Ranch Hand
Posts: 441
Scala IntelliJ IDE Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:

Luigi Plinge wrote: . . . int n = a / 100 % 10 . . .

Are you sure about that? Have you got the / and the % in the right places?



Yes and yes.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic