Vu N. Vu N. - 5 days ago 5
Java Question

Loop for printing array values in two columns

I've been trying to make the following

for
loops to print the original and modified values of an array in two columns, separated by
\t\t
. Here is my code:

public class Main {

public static void main(String[] args) {

int jay[] = {1,2,3,4,5,6};
System.out.println("Original\tAfter");

for(int y: jay) {
System.out.println(y);
}

multiplyByTen(jay);

for(int z: jay) {
System.out.println("\t"+ z);
}

}

public static void multiplyByTen(int x[]) {
for(int counter = 0; counter<x.length;counter++) {
x[counter] *= 10;
}
}
}


This is the result so far:

Original After
1
2
3
4
5
6
10
20
30
40
50
60


So my question is how to align the value 10 to 1, and 20 to 2 and so on?

Answer

replace your printing with this:

int jay[] = {1,2,3,4,5,6};
int jay2[] = jay.clone();
System.out.println("Original\tAfter");
multiplyByTen(jay2);
for (int i = 0; i < jay.length; i++) {
    System.out.println(jay[i]+"\t\t"+jay2[i]);
}

This way, you print table rows and not columns.