TheHacker66 TheHacker66 - 1 month ago 18
Java Question

Java exercise - display table with 2d array

I'm struggling to finish a java exercise, it involves using 2d arrays to dynamically create and display a table based on a command line parameter.

Example:

java table 5

+-+-+-+-+-+
|1|2|3|4|5|
+-+-+-+-+-+
|2|3|4|5|1|
+-+-+-+-+-+
|3|4|5|1|2|
+-+-+-+-+-+
|4|5|1|2|3|
+-+-+-+-+-+
|5|1|2|3|4|
+-+-+-+-+-+


What i have done so far:

public static void main(String[] args) {

int num = Integer.parseInt(args[0]);

String[][] table = new String[num*2+1][num];

int[] numbers = new int[num];
int temp = 0;

for(int i=0; i<numbers.length; i++)
numbers[i] = i+1;

// wrong
for(int i=0; i<table.length; i++){
for(int j=0; j<num;j++){
if(i%2!=0){
temp=numbers[0];
for(int k=1; k<numbers.length; k++){
numbers[k-1]=numbers[k];
}
numbers[numbers.length-1]=temp;
for(int l=0; l<numbers.length; l++){
table[i][j] = "|"+numbers[l];
}
}
else
table[i][j] = "+-";
}
}

for(int i=0; i<table.length; i++){
for(int j=0; j<num; j++)
System.out.print(table[i][j]);
if(i%2==0)
System.out.print("+");
else
System.out.print("|");

System.out.println();}
}


This doesn't work, since it prints 1|2|3|4 in every row, which isn't what I need. I found the issue, and it's because the first for loop changes the array order more times than needed and basically it returns as it was at the beginning.

I know that probably there's a way to achieve this by writing more code, but I always tend to nest as much as possible to "optimize" the code while I write it, so that's why I tried solving this exercise by using less variables and loops as possible.

Answer

You are too complex. Hard to find your error. Straight code follows:

public static void main(String[] args) {


    //int num = Integer.parseInt(args[0]);
    int num = 5; // for test

    // creating 2d array
    int[][] figures = new int[num][num];

    // filling the array
    for(int row=0; row<figures.length; ++row) {
        for(int col=0; col<figures[row].length; ++col) {
            figures[row][col] = (row + col) % num + 1; 
        }
    }

    // printing the array
    for(int row=0; row<figures.length; ++row) {

        // printing border
        for(int col=0; col<figures[row].length; ++col) {
            System.out.print("+-");
        }
        System.out.println("+");

        // printing data row
        System.out.print("|");
        for(int col=0; col<figures[row].length; ++col) {
            System.out.print(figures[row][col]);
            System.out.print("|");
        }
        System.out.println();
    }

    // printing final border
    for(int col=0; col<figures[0].length; ++col) {
        System.out.print("+-");
    }
    System.out.println("+");


}