Not.
Try it. This is normal.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(3*(i-1) + j);
System.out.print(" ");
}
System.out.println();
}
Why does it work?
Ok ... if you follow closely, you will see that i
you have these 3 numbers on the line:
3*(i-1)+1
, 3*(i-1)+2
,3*(i-1)+3
(the last number is a number divisible by 3).
So your general formula.
source to share
When dealing with 2d arrays, have some rc cola drink or play with rc toy. This will help you remember Row, then Column.
You need to fix your second array to match the required numbers.
Like this:
for (int i = 0; i < 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print((3*i)+j);
System.out.print(" ");
}
System.out.println();
}
source to share
The problem is that every time you enter the first one for you, you are overwriting the variable j.
So the sifrs, second and thirt times when you got the correct answer, but in the fourth j is reissued, so you need to do the following:
public static void main(String[] args) {
int j;
int k = 1;
for (int i = 1; i <= 3; i++) {
for (j = i; j <= i + 2; j++) {
System.out.print(k);
System.out.print(" ");
k++;
}
System.out.println();
}
}
Adding a new constant k that stores the number of iterations and prints them as you see fit. Hope this helps!
source to share
A java-8 implementation of the problem
IntStream.range(0, MAX)
.forEach(i -> IntStream.rangeClosed(1, MAX)
.mapToObj(j -> j == MAX ?
String.format("%3d", i * MAX + j) + "\n" :
String.format("%3d", i * MAX + j) + " ")
.forEach(System.out::print)
);
The value MAX
in this case will be 3
.
Conclusion for MAX = 5
-
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
source to share