Developer Developer - 1 year ago 80
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.


public class sample {
public static void main(String[] args) {

String[] animalArray = new String[5];

String animal = "Dog";

case "Dog":
//The position 0 is found using some calculation
animalArray[0] = "Dog";

case "Cat":
////The position 3 is found using some calculation
animalArray[3] = "Cat";

//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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download