java 为案例中未使用的其余索引切换默认值

标签 java switch-statement

我需要使用 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/

相关文章:

java - 务实地检测 MIUI/小米设备中软导航栏的可用性?

java - 压缩提取的 Jar 文件

java - 如果您只有一个写线程,您是否需要特殊的并发性?

c# - 在 C# 中使用 enum 和 struct 代替 switch 语句

java - 从键值(环境)传递到关系(实体)时,Xodus 会生成一个巨大的文件

c# - 如何重用正则表达式变量?

javascript - 外部 JavaScript 和下拉菜单无法在浏览器中正确呈现

java - 在 switch 语句中将值从一种情况传递到另一种情况

C++ switch 语句的用法

java - 如何在 Eclipse 中找到方法实现的用法?