我需要使用 Switch 的默认值来为具有 Cases 中未使用的索引的数组元素赋值。
示例:
public class sample {
public static void main(String[] args) {
String[] animalArray = new String[5];
String animal = "Dog";
switch(animal){
case "Dog":
//The position 0 is found using some calculation
animalArray[0] = "Dog";
break;
case "Cat":
////The position 3 is found using some calculation
animalArray[3] = "Cat";
break;
default:
//How do I get the value of x to be 1,2,4
animalArray[x] = "Undefined";
}
}
}
现在我需要某种方法来告诉 case 语句中尚未使用的索引应该在默认情况下使用。
我该如何实现它?
最佳答案
我会在你使用数组之前预先填充它。
String[] animalArray = new String[5];
Arrays.fill(anumalArray, "undefined");
然后您可以设置任何已知值。
关于java 为案例中未使用的其余索引切换默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39667072/