【问题标题】:is it possible to use the multiple cases in "if condition" to access the same function是否可以在“if条件”中使用多个案例来访问相同的功能
【发布时间】:2019-02-07 00:41:17
【问题描述】:

我需要为所有案例访问相同的函数,因此我在 if 条件中实现了多个案例。由于IDE为此抛出错误,很明显这是错误的实现。但是有什么东西可以替代这种逻辑。

java

 void movie() {
                int m;
                System.out.println("Choose the movie :");
                System.out.println("1.BAHUBALI\n2.SHIVAAY\n3.DANGAL\n4.AIRLIFT");
                m =sc.nextInt();
          switch(m){
                if(case 1: || case 2: || case 3: || case 4:) {
                     Payment();
                }

                else {
                    System.out.println("Choosen an Invlid option");
                }
            }
        }

【问题讨论】:

标签: java switch-statement


【解决方案1】:

由于您在此处进行Integer 比较,您可以使用Map 将比较减少到仅一个条件。类似下面的东西

    Map<String, Integer> map = new HashMap<>();
    map.put("1", 1);
    map.put("2", 2);
    map.put("3", 3);
    map.put("4", 4);

    void movie() {
    int m;
    System.out.println("Choose the movie :");
    System.out.println("1.BAHUBALI\n2.SHIVAAY\n3.DANGAL\n4.AIRLIFT");
    m = sc.nextInt();

    if (map.containsKey(m)) {
        Payment();
    }
    else {
        System.out.println("Choosen an Invlid option");
    }
}

Map.containsKey :如果此映射包含指定键的映射,则返回 true。

因此,最初我们将用户期望的值放入Map 对象中,然后使用containsKey 检查实际用户输入是否存在于对象中。如果是则调用,Payment() 否则,打印一些消息

【讨论】:

  • 你能解释一下吗?
  • @AniketJadhav 更新了我的答案。请看一下
【解决方案2】:

试试这个:-

switch (key) {
        case 1:
        case 2:
        case 3:
        case 4: 
            Payment();
            break;

        default:
            System.out.println("Choosen an Invlid option");
            break;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多