我有一个2d数组,我必须添加一定的值,但只能添加到2d数组的一列。2d数组的一行必须被跳过,并将保持与以前相同。
我已经有了一个代码(见下文),但这只是添加值,而不是计算它。
我的代码:
double lowest = Double.parseDouble(excelMatrix[0][0]);
int row = 0, column = 0;
List usedRow = new ArrayList();
for(int r = 0; r<excelMatrix.length-1; r++){
for(int c = 0; c<excelMatrix[r].length; c++){
double number = Double.parseDouble(excelMatrix[r][c]);
if(lowest > number) {
lowest = number;
row = r;
column = c;
}
}
}
usedRow.add(row);
for(int r = 0; r < excelMatrix.length; r++){
if( r != row)
excelMatrix[r][column] += lowest;
}
初始矩阵看起来像这样:
{1 , 2 , 3 , 4 , 5}
{5 , 4 , 3 , 2 , 1}
{4 , 5 , 1 , 2 , 3}
{2 , 3 , 4 , 5 , 1}
{3 , 4 , 5 , 1 , 2}
,通过在第3列加上10,除了第3行,我想得到:
{1 , 2 , 3 , 14 , 5}
{5 , 4 , 3 , 12 , 1}
{4 , 5 , 1 , 12 , 3}
{2 , 3 , 4 , 5 , 1}
{3 , 4 , 5 , 11 , 2}
但此刻我得到:
{1 , 2 , 3 , 410 , 5}
{5 , 4 , 3 , 210 , 1}
{4 , 5 , 1 , 210 , 3}
{2 , 3 , 4 , 5 , 1}
{3 , 4 , 5 , 110 , 2}
我希望这个例子能使我的问题清楚。谢谢你! 根据您得到的输出,看起来excelMatrix
的类型是String[][]
,所以当您使用+=
运算符时,您正在将数字连接到字符串。
如果将excelMatrix
数组更改为int[][]
,您将得到所需的输出。
如果excelMatrix
必须保持为String[][]
,您仍然可以通过将String
转换为int
,执行加法并转换回String
(尽管效率较低)来执行加法:
excelMatrix[r][column] = Integer.toString(Integer.parseInt(excelMatrix[r][column]) + value);
这段代码可以解决你的问题。
for(int i =0;i<numOfRows;i++) {
for(int j= 0;j<numOfColumns;j++) {
if(i != rowToBeSkipped) {
excelMatrix[i][j] = excelMatrix[i][j] + value;
}
}
}