Developer Developer - 2 months ago 8
Java Question

java Switch default for the rest of indexes not used in the cases

I need to use the Switch's default to assign values to the array elements with indexes that were not used in the Cases.

Example:

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";
}
}
}


Now I need some way to tell that the indexes that were not already used in the case statement should be used here in the default.

How do I implement that?

Answer

I would prefill the array before you use it.

String[] animalArray = new String[5];
Arrays.fill(anumalArray, "undefined");

Then you can set any known values.

Comments