我想从我的程序中打印出2d字符串数组中字符数最多的列的索引
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;
}
到目前为止,我的代码看起来像这样,但我仍然坚持如何比较我的结果,有人可以帮我解释一下如何继续吗?非常感谢你!
答案 0 :(得分:0)
问题出在您的if子句和变量countEach
的位置。 countEach
将在外循环的每次迭代中设置为0
,使得if子句始终为真,因此无效工作。你想要的是使用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;
}