英文:
java 2D integer array looping wrong output
问题
class test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt(); // 输入行数和列数
int twoD[][] = new int[a][];
int z;
for (z = 0 ; z < a ; z++) {
twoD[z] = new int[z + 1];
}
int i, j, k = 0;
for (i = 0 ; i < a ; i++) {
for (j = 0 ; j <= i ; j++){
twoD[i][j] = k;
k++;
}
}
for (i = 0 ; i < a ; i++ ) {
for (j = 0 ; j <= i ; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}
期望输出(当 a = 4):
0
1 2
3 4 5
6 7 8 9
实际输出(当 a = 4):
0
0 0
0 0 0
0 0 0 0
请帮我修复问题。根据我看,循环是正确的。可能其他地方有错误...
英文:
code :
class test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt(); // input number rows & colums
int twoD[][] = new int[a][];
int z;
for (z = 0 ; z < a ; z++) {
twoD[z] = new int[z + 1];
}
int i,j,k = 0;
for (i = 0 ; i < a ; i++) {
for (j = 0 ; j <= i ; j++){
twoD[i][j] = k;
k++;
}
for (i = 0 ; i < a ; i++ ) {
for (j = 0 ; j <= i ; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}
my expected output is ( for a = 4) :
0
1 2
3 4 5
6 7 8 9
my output is (for a = 4):
0
0 0
0 0 0
0 0 0 0
please help me fix my problem. according to me the lopping is correct. there might be mistake somewhere else...
答案1
得分: 1
以下是翻译好的内容:
2D数组内容打印循环包含在应该用于填充2D数组值的循环内。由于它使用相同的变量,它干扰了第一个循环的执行。将其移出:
int i, j, k = 0;
for (i = 0; i < a; i++) {
for (j = 0; j <= i; j++) {
twoD[i][j] = k;
k++;
}
}
for (i = 0; i < a; i++) {
for (j = 0; j <= i; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
你可以通过以下方式避免这个问题:
- 使用自动格式化代码的编辑器或IDE,以便显示控制结构的嵌套关系
- 使用常见的习惯用法,比如用最小必要作用域声明循环变量:
for (int i = 0; i < a; i++)
英文:
The loop that prints the contents of the array is contained within the loop that is supposed to fill the 2D array with values. Since it uses the same variables, it interferes with the execution of the first loop. Move it out:
int i,j,k = 0;
for (i = 0 ; i < a ; i++) {
for (j = 0 ; j <= i ; j++){
twoD[i][j] = k;
k++;
}
}
for (i = 0 ; i < a ; i++ ) {
for (j = 0 ; j <= i ; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
You could have avoided this by
- using and editor or IDE that automatically formats your code, so that is shows you how the control structures are nested
- using common idioms like declaring the loop variables with the smallest necessary scope:
for (int i = 0 ; i < a ; i++)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论