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

Java - enhanced for loop printing values

I've been trying to make the following enhanced for loops to print an "original" array and its "after" array to be next to each other with a "\t\t", but I achieved no result so far. 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;
}
}
}


the unwanted result:

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


So my question is how to make the value 10 to be aligned next to 1, and 20 next to 2, and etc?

Edit: I'm actually learning about Arrays in Methods, so I want to know how to do that without changing the core of this code.

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.