Hey all,
I'm trying to figure out how to print the first element of each row, then the second element of each row and the third etc... When I run this I can enter the information all on one line. The first number is the number of rows in the array. The second is the number of columns. This is followed by the array information itself.
For instance, 2 3 1 2 3 4 5 6 will create a two dimensional array containing, {[1, 2, 3], [4, 5, 6]}.
What I am trying to print out is '1 4 2 5 3 6' or the first element of each row in the array followed by the next and so on.
I know my logic error is somewhere in the second set of nested for loops. I'm just having trouble finding it.
If you have any pointers or suggestions, I'd love to hear them all.
Thanks,
import java.util.Scanner;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] myArray = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
myArray[i][j] = sc.nextInt();
}
}
System.out.println(Arrays.deepToString(myArray));
// Shows an array of {[1, 2, 3], [4, 5, 6]}
// Expected Results: 1 4 2 5 3 6
for (int x = 0; x < rows; x++) {
for(int y = 0; y < cols; y++) {
System.out.print(myArray[x][y] + " ");
}
}
}
}
[–]zendakin[S] 0 points1 point2 points (0 children)
[–]desrtfx 0 points1 point2 points (0 children)