我想按列计算String [][]
中的字母数,到目前为止,我的代码是:
for(int j = 0 ; j<matrix[0].length ;j++){
for(int i = 0 ; i< matrix.length ;i++ )
if (Character.isLetter(matrix[j][i].charAt(j)))
countChar++;
}
System.out.println(countChar + "letters");
return countChar;
但程序的输出计算字符串有多少元素 例如,如果String是:
String [][] C = {
{"abc", "abcd" , "abcd"},
{"oroeo", "kakakak" , "alsksjk"},
{"abcdef", "asdasdasdasd", "asdasdasdasd"},
};
结果是9,但应该是14(按列的字母数) 任何帮助都非常值得感谢!
答案 0 :(得分:0)
您可以将2D矩阵定义为行数组或列数组。我假设您已将其定义为行数组,现在想要获取某列中的值。
所以你的数据是这样的:
abc abcd abcd
oroeo kakakak alsksjk
abcdef asdasdasdasd asdasdasdasd
三行三列。
获取中间列(索引为1)中的值,您需要获取数组元素:
matrix[0][1]
matrix[1][1]
matrix[2][1]
我认为您正在尝试计算每列中所有值的总长度。那会是这样的:
// assume that the matrix has at least one row and thas the same number of columns in each row
// take the number of columns in the first row for reference
int numberOfColumns = matrix[0].length;
for(int col = 0; col < numberOfColumns; col++) {
int count = 0;
// iterate over all the rows
for(String[] row : matrix) {
// count the length of the element in position col of this row
count += row[col].length();
}
System.out.printf("%s characters in column %s", count, col);
}
答案 1 :(得分:0)
int n = 0;
// iterate row by row
for (int i = 0; i < C.length; i++) {
n += C[i][0].length();
// get the string at index 0 (or 1 or 2.. whichever you want) of the array and append its length
// if you expect the string to contain numbers, then
// run a for-loop on the string and check if its a letter
}
System.out.println(n);
答案 2 :(得分:0)
尝试下面的问题是你的for循环的no。迭代的范围仅限于矩阵的大小:
for(int i = 0 ; i<C[0].length ;i++) {
String matrixElement = C[i][0];
System.out.println(matrixElement);
for(int k =0 ;k < matrixElement.length();k++)
if (Character.isLetter(matrixElement.charAt(k)))
countChar++;
}
答案 3 :(得分:0)
请格式化你的代码并刷新循环:
private static int countByColumn(String[][] matrix, int column) {
if (column < 0)
return 0; // Or throw exception
int countChar = 0;
for (String[] line : matrix) {
//DONE: jagged array: it may appear that the line is too short
if (line.length <= column)
continue;
String item = line[column];
for (int i = 0; i < item.length; ++i)
if (Character.isLetter(item.charAt(i)))
countChar += 1;
}
return countChar;
}
测试:
// 14
int test = countByColumn(C, 0);