通过以下代码,我希望将以相同名称开头的所有字母组合到一个数组列中,在第二列中,我想保留与字母相关的数字的总和。
例如 :
array_1 = { {"bat","1"},
{"rat","2"},
{"ball","3"},
{"run","4"},
{"lizard","5"}
}
into array_2 = { {"b","4"},
{"r","6"},
{"l",5}
}
以下代码给出了一半正确的结果。当ball
它再次到达它时,问题会添加下一个以开头的字母b
并将其存储为单独的值。问题是第 42 行。我已经标记了。我应该如何检查它是否添加了字母表的编号。
package keylogger;
import java.util.Arrays;
public class ArrayTester {
private static int finalLength=0;
private static String firstAlphabet[][];
private String data[][] = {
{"Nokia" , "7"},
{"Blackberry" , "1"},
{"Nimbus","10"},
{"Apple","19"},
{"Ami","21"},
{"Bug","35"},
{"Native","200"},
{"zebra","100"},
{"Nine","9"}
};
public void calculator() {
try {
// traverse the whole array
firstAlphabet = new String[data.length][data.length]; // set the length of firstAlphabet array
for(int i=0;i<data.length;i++) {
firstAlphabet[i][0] = data[i][0].substring( 0, 1); // get the first alphabet
firstAlphabet[i][1] = data[i][1];
int k = i+1;
int v = k;
int t=0;
for(int j=0;j<data.length-v;j++) {
System.out.println("Inner for loop" + j);
String s = data[k][0];
// line 42:
if(firstAlphabet[i][0].compareToIgnoreCase(s.substring(0, 1))==0) {
System.out.println("If statement");
firstAlphabet[i][0] = s.substring(0, 1);
Integer z = Integer.parseInt(data[k][1]) + Integer.parseInt(firstAlphabet[i][1]);
firstAlphabet[i][1] = z.toString();
}
k++;
}
}
}catch(Exception exc) {
exc.printStackTrace();
}
}
public static void main(String args[]) {
ArrayTester o = new ArrayTester();
o.calculator();
for(String s[] : firstAlphabet) {
for(String x : s) {
System.out.println(x);
}
}
}
}
输出
Inner for loop0
Inner for loop1
If statement
Inner for loop2
Inner for loop3
Inner for loop4
Inner for loop5
If statement
Inner for loop6
Inner for loop7
If statement
Inner for loop0
Inner for loop1
Inner for loop2
Inner for loop3
If statement
Inner for loop4
Inner for loop5
Inner for loop6
Inner for loop0
Inner for loop1
Inner for loop2
Inner for loop3
If statement
Inner for loop4
Inner for loop5
If statement
Inner for loop0
If statement
Inner for loop1
Inner for loop2
Inner for loop3
Inner for loop4
Inner for loop0
Inner for loop1
Inner for loop2
Inner for loop3
Inner for loop0
Inner for loop1
Inner for loop2
Inner for loop0
Inner for loop1
If statement
Inner for loop0
N
226
null
null
null
null
null
null
null
B
36
null
null
null
null
null
null
null
N
219
null
null
null
null
null
null
null
A
40
null
null
null
null
null
null
null
A
21
null
null
null
null
null
null
null
B
35
null
null
null
null
null
null
null
N
209
null
null
null
null
null
null
null
z
100
null
null
null
null
null
null
null
N
9
null
null
null
null
null
null
null
如果我们注意到与字母相关的总和是正确的。唯一的问题是重复。即例如 N=219 即 200+19