aspose file tools*
The moose likes Beginning Java and the fly likes Position of Numbers? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Position of Numbers?" Watch "Position of Numbers?" New topic
Author

Position of Numbers?

Jacob Coddaire
Ranch Hand

Joined: Jan 11, 2011
Posts: 36

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

Joined: Jan 06, 2011
Posts: 441

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

Joined: Oct 02, 2003
Posts: 11476
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39826
    
  28
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

Joined: Aug 30, 2010
Posts: 29
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

Joined: Jan 06, 2011
Posts: 441

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Position of Numbers?