我有一个函数,它给出了一个int数组的输出,其总长度为5,其中值为1或0.这里有一些可能的输出示例:
[1, 1, 0, 1, 0] or [0, 0, 1, 0, 1] or [1, 1, 1, 1, 1]
使用它作为输入,我需要在Java中创建一个函数,它将这个int数组与一个字符串数组相关联,其中1表示该字符串将在数组中,0表示它赢得了#39 ; t在数组中。例如:
[1, 1, 1, 1, 1] => ["Tweet", "Email", "Text", "Phone Call", "Voicemail"]
[0, 1, 1, 0, 1] => ["", "Email", "Text", "", "Voicemail"]
[0, 0, 0, 0, 0] => ["", "", "", "", ""]
我能想到的就是做这样的事情:
public String[] myFunc(int[] arr) {
String[] output = [5];
for (int i = 0; i < arr.length; i++) {
switch (i) {
case 0:
if (arr[i] == 1)
output[i] = "Tweet";
else
output[i] = "";
break;
case 1:
if (arr[i] == 1)
output[i] = "Email";
else
output[i] = "";
break;
case 2:
if (arr[i] == 1)
output[i] = "Text";
else
output[i] = "";
break;
case 3:
if (arr[i] == 1)
output[i] = "Phone Call";
else
output[i] = "";
break;
case 4:
if (arr[i] == 1)
output[i] = "Voicemail";
else
output[i] = "";
break;
}
}
return output;
}
这是一个非常丑陋的解决方案,我确信通过实现某种对象来映射值可以更好地完成它,但我不太熟悉Java并且会感激任何帮助!
答案 0 :(得分:0)
试试这个
boolean[] booleanArray = new boolean[] { true, false, true, false, true };
String[] stringArray = new String[] { "Tweet", "Email", "Text", "Phone Call", "Voicemail" };
String[] stringResult = new String[5];
for (int i=0;i<booleanArray.length;i++) {
if (booleanArray[i]) {
stringResult[i] = stringArray[i];
} else {
stringResult[i] = "";
}
}