Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Position of Numbers?

 
Jacob Coddaire
Ranch Hand
Posts: 36
Chrome Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • 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?

 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • 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()
 
fred rosenberger
lowercase baba
Bartender
Posts: 12086
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • 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.
 
Campbell Ritchie
Sheriff
Posts: 48404
56
  • Mark post as helpful
  • send pies
  • 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?
 
palanisamy subramani
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • 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
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic