我有一个二维数组,我必须向其中添加某个值,但仅限于二维数组的一列。二维数组的一行必须跳过并保持与之前相同。
我已经有一个代码(见下文),但这只是添加值,而不是计算它。
到目前为止我的代码:
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}
通过将 10 添加到第 3 列(第 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);
关于java:将一个值添加到二维数组中的一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38941363/