Fizzix Fizzix - 1 month ago 10
Java Question

How to move positions within an array in Java?

A program that simply moves array elements.

Two variables:

userInputVariable
and
blankSpaceVariable
.

I have a 2D array named table. Defined as
table[userInputVariable + 1][6]


I am printing out this array in a table format, and the far left column is numbered by whatever number the user entered at the beginning of the program.

I then ask the user where they would like to enter a blank space within the array. This blank space acts like a divider for all the other information in the array.

For example, if the user enters 10 at the start for the
userInputVariable
, and then enters 5 for the blank space. Once printed, the numbers should go like this:

1, 2, 3, 4, --, 5, 6, 7, 8, 9, 10.

My plan has been to create a for loop and try to move all the numbers in the array back a position starting from the blank space variable.

What I currently have, but does not work:

for (int i = blankSpaceVariable; i < table.length - 1; i++)
{
table[i] = table[i + 1];
}
table[blankSpaceVariable] = "--";


With my current code, the numbers go like this:

1, 2, 3, 4, 6, 7, 8, 9, 10

Tried completing this a few different ways also, but the other info within my 2D array didn't move with the numbers. So I thought that this approach can hopefully move all the info within my 2D array down, and make way for a blank section.

All help is greatly appreciated!

Answer

If you want to move numbers to the next position, then you should start from the end of the array.

for (int i = table.length - 1; i > blankPosition; i--) {
    table[i] = table[i - 1];
}
table[blankPosition] = 99;

From your example, it could be necesary to substract 1 from blankPosition (you say if blankPosition is 5, then the table[4] has the --), but this probably would be good to do before entering the loop (it's a matter of formatting the data for the actual implementation).

And probably renaming table would be a good idea, too.


Really nasty example implementation:

public class Arrays {

        public static void main(String[] args) {
                Integer blankPosition = Integer.parseInt(args[0]);
                // Using 99 instead of "--" because of array type
                int[] table = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 99};
                printEm(table);
                for (int i = table.length - 1; i > blankPosition; i--) {
                        table[i] = table[i - 1];
                }
                table[blankPosition] = 99;
                printEm(table);
        }

        public static void printEm(int[] array) {
                for(int i = 0; i < array.length; i++) {
                        System.out.print(array[i] + " ");
                }
                System.out.println();
        }
}

Let's run it:

$ java Arrays 5
1 2 3 4 5 6 7 8 9 10 99 
1 2 3 4 5 99 6 7 8 9 10
Comments