比如我的数组是
String[][] str1 = null;
str1[0] [0]="a";
str1[0] [1]="1"; str1[1] [0]="b";
str1[1] [1]="2";str1[2] [0]="a";
str1[2] [1]="3";str1[3] [0]="c";
str1[3] [1]="6";
我想让0项相同的行的1项相加得到
str1[0] [0]="a";
str1[0] [1]="4"; str1[1] [0]="b";
str1[1] [1]="2";str1[2] [0]="c";
str1[2] [1]="6";请问我应该怎么做 谢谢
String[][] str1 = null;
str1[0] [0]="a";
str1[0] [1]="1"; str1[1] [0]="b";
str1[1] [1]="2";str1[2] [0]="a";
str1[2] [1]="3";str1[3] [0]="c";
str1[3] [1]="6";
我想让0项相同的行的1项相加得到
str1[0] [0]="a";
str1[0] [1]="4"; str1[1] [0]="b";
str1[1] [1]="2";str1[2] [0]="c";
str1[2] [1]="6";请问我应该怎么做 谢谢
* @param args
* @author (JJ.W)
*/ public static void main(String[] args) {
// TODO 自动生成方法存根
String[][] str1 = new String[4][2];
str1[0][0] = "a";
str1[0][1] = "1"; str1[1][0] = "b";
str1[1][1] = "2"; str1[2][0] = "a";
str1[2][1] = "3"; str1[3][0] = "c";
str1[3][1] = "6"; int X = 0;
int length = 4;// 数组的行数,即问题规模
int changestation = length - 1;// 记录下一个可以填补已经加过的数据位置
for (int i = 0; i < length - X - 1; i++) {
for (int j = i + 1; j < length - X; j++)
if (str1[i][0].equals(str1[j][0])) {
str1[i][1] = String.valueOf(Integer.parseInt(str1[j][1])
+ Integer.parseInt(str1[i][1]));
str1[j][0] = String.valueOf(str1[changestation][0]);// 将该位置填补!
str1[changestation][0] = "0";// 设置为不可用
str1[j][1] = String.valueOf(str1[changestation][1]);// 将该位置填补!
changestation--;
X++; }
} for (int i = 0; i < changestation + 1; i++) { System.out.print(str1[i][0]);
System.out.println(str1[i][1]); } }
}
------------------------------------------
呵呵 第一次写 有点乱 仅供参考,也希望大家批评!
再发一次!
public class Test2 { /**
* @param args
* @author (JJ.W)
*/ public static void main(String[] args) {
// TODO 自动生成方法存根
String[][] str1 = new String[4][2];
str1[0][0] = "a";
str1[0][1] = "1"; str1[1][0] = "b";
str1[1][1] = "2"; str1[2][0] = "a";
str1[2][1] = "3"; str1[3][0] = "c";
str1[3][1] = "6"; int X = 0;
int length = 4;// 数组的行数,即问题规模
int changestation = length - 1;// 记录下一个可以填补已经加过的数据位置
for (int i = 0; i < length - X - 1; i++) {
for (int j = i + 1; j < length - X; j++)
if (str1[i][0].equals(str1[j][0])) {
str1[i][1] = String.valueOf(Integer.parseInt(str1[j][1])
+ Integer.parseInt(str1[i][1]));
str1[j][0] = String.valueOf(str1[changestation][0]);
// 将该位置填补!
str1[changestation][0] = "0";// 设置为不可用
str1[j][1] = String.valueOf(str1[changestation][1]);
// 将该位置填补!
changestation--;
X++; }
} for (int i = 0; i < changestation + 1; i++) { System.out.print(str1[i][0]);
System.out.println(str1[i][1]); } }
}
str1[0][0] = "a";
str1[0][1] = "1";str1[1][0] = "b";
str1[1][1] = "2";str1[2][0] = "a";
str1[2][1] = "3";str1[3][0] = "c";
str1[3][1] = "6";str1[4][0] = "a";
str1[4][1] = "6";
这样好像就不行了
把if改为while就OK了!
还有这个length要跟着更新才行!