permaculture playing cards*
The moose likes Java in General and the fly likes Swaping Numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Swaping Numbers" Watch "Swaping Numbers" New topic
Author

Swaping Numbers

Sam Benry
Ranch Hand

Joined: Mar 21, 2008
Posts: 89
lets say we have
long n = 987654321;

I want to create a loop to make
n = 897654321
n = 879654321
....
n = 798654321
n = 789654321
....
n = 698754321
....
n = 123456789

I'm really confused on how to make this loop, can anyone help me?
I started with the basics, but this is not even close to what i want to make.
Please help, thanks
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37950
    
  22
More of a beginner's question.

I am afraid you are right, you are nowhere near.

Try getting the number into an int[] array by using the / and % operators, then work out how to swap a pair of numbers, then work out how to use the swap method to reverse the array, then put the array back into a number.

Hint: I wrote about swapping and reversing arrays about 3 months ago. You will need a swap method and a reverse method which uses swap. Both methods sound good candidates for static methods.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
As an aside, the best method to convert a number into a String is the String.valueOf method.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
imaya Munusamy
Greenhorn

Joined: May 19, 2008
Posts: 20
try this
long n = 987654321;
for(int i=1;i<15;i++)
{
int j = i % 9;
long f = (long) (n % (Math.pow(10 ,9-j )) * Math.pow(10, j));
long l = (long) (n / (Math.pow(10 ,9-j ))) ;
System.out.println(j + " - " + ( f + l) );
}
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37950
    
  22
Welcome to JavaRanch, Imaya Munusamy

You are on the right lines, but I think Sam wants division by 10, not 9.

We have a policy of not simply giving answers to that sort of question, but hints, and I think your post provides a very good hint for Sam Benry to work from.

Please don't post a refinement of that method, Imaya, but Sam, please use that as a start and work out what you are going to do. You will remember it a lot better after working it out for yourself.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Swaping Numbers
 
Similar Threads
Methods
Number Conversion to German Format!!
Exception declaration not seen
trouble with loops and invoking a method
loops and boolean operators