gpt4 book ai didi

java - 为二维数组编写 for 循环?

转载 作者:行者123 更新时间:2023-12-01 12:57:35 26 4
gpt4 key购买 nike

我有一个程序,用户为程序提供数组的大小,即(列和行的大小),并且我试图为数组中的每个位置提供相同的值。不过,我的循环有问题,就是这样。

for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//CODE
}
}

我可以看到问题是我试图为不存在的职位赋予值(value),但我不知道如何解决这个问题。任何帮助将不胜感激:)

最佳答案

尝试使用长度,而不是用户输入:

  // ask user for sizes
int col = ...;
int row = ...;

// declare the array, let it be of type int
// it's the last occurence of "row" and "col"
int[][] data = new int[row][col];

// loop the array
for (int r = 0; r < data.length; ++r) { // <- not "row"!
int[] line = data[r];

for (int c = 0; c < line.length; ++c) { // <- not "col"!
// do what you want with line[c], e.g.
// line[c] = 7; // <- sets all array's items to 7
}
}

使用实际数组的维度只是阻止您访问不存在的项目

关于java - 为二维数组编写 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23754325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com