我希望从下面的代码中获得此输出,但总是出现问题:
XX0 0.503
XX1 0.4
XX2 0.2
XX3 0.303
XX4 0.4
XX5 0.002
String[] sarray = new String[]{"XX0", "XX0", "XX0", "XX0", "XX1", "XX2", "XX3", "XX3", "XX3", "XX4", "XX5"};
double [] amount = new double[]{0.2, 0.001, 0.002, 0.4, 0.2, 0.001, 0.3, 0.002, 0.4, 0.002, 0.002};
String s;
double x=amount[0];
try{
for(int i=0;i< sarray.length;i++){
s = sarray[i];
while(sarray[i+1].equals(s)){
amount[i]=amount[i]+amount[i+1];
sarray[i+1]= "";
amount[i+1]=0;
s = sarray[i+1];
}
}
}catch(Exception ex){}
for(int i=0;i< sarray.length;i++){
System.out.println(sarray[i]+" "+amount[i]);
}
}
此代码有什么问题?
答案 0 :(得分:0)
根据我的理解,您正在尝试添加sarray
和amount
数组的相应值。因此,XX0
应该等于0.2 + 0.001 + 0.002 + 0.4
= 0.603
而不是0.503
。
假设是这种情况,您可以尝试以下代码:< / p>
String [] sarray = new String [] {“XX0”,“XX0”,“XX0”,“XX0”,“XX1”,“XX2”,“XX3”,“XX3”,“XX3”,“ XX4“,”XX5“};
double [] amount = new double [] {0.2,0.001,0.002,0.4,0.2,0.001,0.3,0.002,0.4,0.002,0.002};
double x=amount[0];
int i;
try{
for(i=1;i<sarray.length;i++){
if(sarray[i-1].equals(sarray[i])){
x += amount[i];
}
else {
System.out.println(sarray[i-1]+" "+x);
x = amount[i];
}
}
System.out.println(sarray[i-1]+" "+x);
}catch(Exception ex){}
注意:这不会像您一样编辑数组,而是提供所需的输出。