[英]Java: 2d array columns and rows
Thank you for taking the time to read, 感谢您抽出宝贵的时间阅读,
I have a 2d matrix of booleans and im trying to change each of the border values to false. 我有一个布尔的二维矩阵,我试图将每个边界值更改为false。 I have this working for the top and left-most borders but cant seem to figure out a working code for the bottom and right-most, any help would be appreciated, these are the codes for the upper and left-most:
我已经为顶部和最左侧的边界工作了,但似乎无法找出底部和最右侧的工作代码,将不胜感激,这些是顶部和最左侧的代码:
// Changes border values to false //将border值更改为false
for (int row = 0; row <matrix.length; row++) {
int col = 0;
matrix[row][col] = false;
}
for (int col = 0; col <matrix.length; col++) {
int row = 0;
matrix[row][col] = false;
}
Make the row and col values the last values instead of zero; 将row和col值设为最后一个值而不是零;
for the last column: 对于最后一列:
for (int row = 0; row <matrix.length; row++) {
int col = matrix[0].length-1;
matrix[row][col] = false;
}
and last row: 最后一行:
for (int col = 0; col <matrix[0].length; col++) {
int row = matrix.length-1;
matrix[row][col] = false;
}
Or better aproach to avoid creating new instances of col
s and row
s inside the loops; 或者更好的方法是避免在循环内创建
col
或row
的新实例;
for (int row = 0; row <matrix.length; row++) {
matrix[row][matrix[0].length-1] = false;
}
for (int col = 0; col <matrix[0].length; col++) {
matrix[row][matrix.length-1] = false;
}
For col, the last value must be the length of a row, so I write matrix[0].length
it might be any other suitable number too instead of 0, but out of bounds. 对于col,最后一个值必须是一行的长度,因此我写了
matrix[0].length
它也可能是任何其他合适的数字,而不是0,但超出范围。
Well, the easiest way I can think of is to just set row
to the max value of rows through the loop (looks to be matrix.length - 1
each time) as well. 好吧,我能想到的最简单的方法就是通过循环将
row
设置为row
的最大值(看起来是matrix.length - 1
每次为matrix.length - 1
)。 So, for example: 因此,例如:
for (int row = 0; row < matrix.length; row++) {
matrix[row][0] = false;
matrix[row][matrix.length - 1] = false;
}
and do the same for your columns. 并对您的列进行相同操作。
Or something like that; 或类似的东西;
for(int c=0;c<matrix.length;c++){
System.out.println("");
for(int r=0;r<matrix[0].length;r++){
if(c==0||r==0||c==matrix.length-1||r==matrix[0].length-1){
matrix[c][r] = false;
}else{
matrix[c][r] = true;
}
System.out.print(" " + matrix[c][r]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.