我有一个字符串数组[x,y,z]和一个int数组[2,3,4],我需要通过附加两个来创建一个数组,但最后3个值乘以整数int数组,如下: [X,Y,Z,XX,YYY,ZZZZ]。我无法弄清楚如何做到这一点。 我写的是:
public static String[] bigArr (String[] letters, int[] numbers) {
int l = letters.length;
int n = numbers.length;
String[] answer = new String[l+n];
for (int i=0; i<n;i++){
answer[i]=letters[i]+numbers[i];
}
return answer;
}
显然它在这一点上是胡说八道,但我被困住了,需要一个很好的解释如何做到这一点。我是Java的新手。
答案 0 :(得分:0)
1。首先,将字母复制到answer
2。然后,对于每个字母l[i]
,
answer[l + i - 1] = string_consisting_of_letter_l[i]_repeated_n[i]_times
答案 1 :(得分:0)
试试这个:
public static void main(String[] args) throws Exception {
String[] letters = {"x", "y", "z"};
int[] numbers = {2, 3, 4};
String[] result = bigArr(letters, numbers);
// prints [x, y, z, xx, yyy, zzzz]
System.out.println(Arrays.toString(result));
}
private static String[] bigArr(String[] letters, int[] numbers) {
int lettersLength = letters.length;
int numbersLength = numbers.length;
String[] result = new String[lettersLength + numbersLength];
for (int n = 0; n < lettersLength; ++n) {
result[n] = letters[n];
}
StringBuilder sb = new StringBuilder();
for (int n = lettersLength; n < result.length; ++n) {
sb.setLength(0); // reset the StringBuilder
for (int m = 0; m < numbers[n - lettersLength]; ++m) {
sb.append(letters[n - lettersLength]);
}
result[n] = sb.toString();
}
return result;
}