I wanna ask you something about my code. I want to display output as below:
2 3 4 1
6 7 8 5
10 11 12 9
14 15 16 13
But the output what is shown:
2 3 4 1
6 3 0 -3
2 -1 -4 -7
-2 -5 -8-11
Here is my current code:
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
System.out.printf("%3d", number);
if(j==2){
plus=-3;
}
number+=plus;
}
number+=8;
System.out.println("");
}
Can you tell me what's wrong with it? Thank you
You need to reset plus
to 1
at the end of each iteration of the outer loop. See the below code in action here .
int number = 2;
int plus = 1;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.printf("%3d", number);
if (j == 2) {
plus = -3;
}
number += plus;
}
number += 8;
plus = 1;
System.out.println("");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.