Reputation: 675
I'm trying to made a method that receives a matrix and prints its lines. For example:
line nb 1 : 3 2 5 6
line nb 2 : 7 9 0 1 4 3
line nb 3 : 3 5 3
I'd like to know why I cannot print the lines of the given matrix using this code. And also, why I cannot increment the variable k
, that shows me the number of the line.
When I run this code it does not increment k
. It always shows me the number 1
for the line
How can I fix my code?
public static void PrintLine(int[][] matrix){
for (i = 0; i < matrix.length; ++i){ // Loop all long the lines of the matrix
int k = 1; // Number of the line
System.out.print("Line nb " + k + matrix[i]);
k = k+1; // Increment the number of the line by 1
}
}
Upvotes: 0
Views: 55
Reputation: 2390
As other have pointed out the scope of your k
is incorrect, you can just use the value of i
, also when you print your array you are getting the object reference details, you can use Arrays.toString()
to print the values from an Array.
for (int i = 0; i < matrix.length; ++i) {
System.out.print("Line nb " + i +": "+ Arrays.toString(matrix[i]));
}
Upvotes: 0
Reputation: 6385
Your k
variable is initialized inside for
loop. It means on each iteration it will be new variable. With initial 1 value.
Move it's itialization out of the loop:
int k = 1; // Number of the line
for (i = 0; i < matrix.length; ++i){ // Loop all long the lines of the matrix
Upvotes: 0
Reputation: 1101
It's not so much that k
does not get incremented; rather, you increment k
only to discard it immediately, because the scope of the variable k
is restricted to a single iteration (i.e., within the curly braces). The following should work:
for (int i = 0, k = 0; i < matrix.length; ++i, ++k) {
/* work in terms of i and k */
}
which, in your case, simplifies to using i
and k
for the same purpose:
for (int i = 0; i < matrix.length; ++i) {
System.out.print("Line nb " + i + matrix[i]");
}
Upvotes: 1