[英]compare the sum of characters in a 2d array of strings
我想从程序中打印二维字符串数组中字符数最多的列的索引
public static int columns(String [][] matrix) {
int numCol = matrix[0].length;
int indexCol = -1;
for(int col = 0; col < numCol; col++) {
int count = 0;
int countEach = 0;
for(String[] row : matrix) {
count += row[col].length();
if(count > countEach){
countEach = count;
}
System.out.println("count one by one (rows) : " + countEach +" "+"Column :" + col);
}
System.out.println();
System.out.println("SumChar : " + count +" " + "column : "+col + "###############");
}
System.out.println("Index of the highest array of characters by columns : ");
return indexCol;
}
到目前为止,我的代码看起来像这样,但是我仍然坚持如何比较我的结果,有人可以请我解释如何继续吗? 非常感谢你!
问题出在您的if子句以及变量countEach
的位置。 每次外部循环迭代时, countEach
都将设置为0
,从而使if子句始终为true,因此将无用。 您想要使用countEach
作为变量,该变量保留某些列具有的最大字符数的值。 这样,您就可以将if子句传递到外部循环,并向其中添加具有更多字符的列索引的更新。
检查以下修改:
完整代码
public static int columns(String [][] matrix) {
int numCol = matrix[0].length;
int indexCol = -1;
int countEach = 0; // Put countEach outside the for loop
for(int col = 0; col < numCol; col++) {
int count = 0;
for(String[] row : matrix) {
count += row[col].length();
System.out.println("count one by one (rows) : " + count +" "+"Column :" + col);
}
// Move if clause to here
if(count > countEach){
countEach = count;
indexCol = col; // Update column index with more chars
}
System.out.println("SumChar : " + count +" " + "column : "+col + "###############");
System.out.println();
}
System.out.println("Index of the highest array of characters by columns : ");
return indexCol;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.