# Array Help

• 11-23-2009, 12:09 PM
jkhamler
Array Help
I'm writing a method to take an integer from the user and swap each pair of digits starting from the least significant.

E.g., if the method is called with 232563 it would return 325236, or 1804982 returns 1089428. In the second case, the most significant digit, the "1", has no digit to swap with so remains in the same position.

So I've made it accept and integer input and convert it into an array of chars, but I'm stuck on how to do the swapping operation. I don't want the code - just some ideas on how to approach it. Could anybody help?

Many thanks,

Jonathan
• 11-23-2009, 01:30 PM
sky
You could check de length of the array and then swap the elements of the positions array[0] and array[length-1] using a aux variable.
• 11-23-2009, 04:49 PM
Tolls
Loops backwards through the array, using a starting index of the last element (length-1).
In each cycle you will swap the current index entry with the one at index-1 (ie the previous entry).
Decrement the index by 2 each time.
Keep doing this while your index > 0.

You shouldn't need a new array to work with, just use the existing one...unless you feel you need a new one to try and keep things straight in your head.
• 11-24-2009, 12:49 AM
jkhamler
Ok great thanks... I'll let you know how I get on!
• 11-24-2009, 11:06 PM
jkhamler
Ok I need some help with my syntax... I've got into a bit of a muddle mixing up ints and chars... this is as far as I've got:

public class Q3
{
public static void main (final String [] args)
{
KeyboardInput in = new KeyboardInput() ;
System.out.println("Please enter an integer: ") ;
System.out.print("Digits reversed: "+digitSwap(a)) ; //calls 'digitSwap' method
}

public static int digitSwap(int a) // "digit swap" method
{
String s = a+"" ; // Converts integer to string
char[] arr = s.toCharArray(); // Converts string to array of chars

for (int i = arr.length-1; i > 0; i=i-2); // loops backwards through the array
{
int swapArr = arr[i];
arr[i] = arr[i-1]; // swaps current index entry with the previous entry
arr[i-1] = swapArr;

}
String str = new String(arr); // Converts array of chars back into a string
int i = Integer.valueOf(str); // Converts string back into an integer
return i;
}

}
• 11-25-2009, 10:02 AM
Tolls
Use code tags when posting code. That's the first thing, because otherwise we're looking at unformatted code which I find very difficult to read quickly.

You ought to also tell us what errors you're getting...compiler errors in this case.
However:

Code:

`for (int i = arr.length-1; i > 0; i=i-2);`
your for loop does nothing due to that pesky semi colon.

And once you've done that, you have an array of chars, which is fine, but what are you putting into this array here:
Code:

`arr[i-1] = swapArr;`
?