如何在同一个数组中连接两列?
示例:
AA AB AC AD
1 0 2 0
2 1 3 3
3 3 0 2
0 2 1 1
输出:应该是这样的。
AAAB AAAC AAAD ABAC ABAD ACAD
10 12 10 02 00 20
21 23 23 13 13 33
33 30 32 30 32 02
02 01 01 21 21 11
我如何在java中编写代码?
for(int i = 0; i< row.size(); i ++){
for(int j = 0; j< col.size(); j ++){
for(int k = j + 1; k< col.size(); k ++){
col1.add(VAL [J]);
col2.add(VAL [K]);
finalval.add(col1.get(j)+ col2.get(k));
}
}
的System.out.println( “finalval”);
}
答案 0 :(得分:2)
public static void main(String[] args) {
String[][] elements = new String[][] {
{ "AA", "AB", "AC", "AD" },
{ "1", "0", "2", "0" },
{ "2", "1", "3", "3" },
{ "3", "3", "0", "2" },
{ "0", "2", "1", "1" }
};
for (int row = 0; row < elements.length; row++) {
for (int col = 0; col < elements[0].length; col++) {
for (int x = col + 1; x < elements[0].length; x++) {
System.out.print(elements[row][col] + elements[row][x] + " ");
}
}
System.out.println();
}
}
输出:
AAAB AAAC AAAD ABAC ABAD ACAD
10 12 10 02 00 20
21 23 23 13 13 33
33 30 32 30 32 02
02 01 01 21 21 11
答案 1 :(得分:0)
public static void main(String[] args) {
String[][] input = new String[][] { { "AA", "AB", "AC", "AD" },
{ "1", "0", "2", "0" },
{ "2", "1", "3", "3" },
{ "3", "3", "0", "2" },
{ "0", "2", "1", "1" } };
String[][] output = new String[input.length][];
for (int i = 0; i < output.length; i++)
output[i] = concat(input[i]);
print(output);
}
private static String[] concat(String[] strings) {
int n = strings.length;
String[] result = new String[(n * (n - 1)) / 2];
int m = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (i != j)
result[m++] = strings[i] + strings[j];
return result;
}
private static void print(String[][] strings) {
for (int i = 0; i < strings.length; i++)
System.out.println(Arrays.asList(strings[i]));
}