【问题标题】:using switch block in java instead of multiple if statements在java中使用switch块而不是多个if语句
【发布时间】:2011-06-29 22:06:52
【问题描述】:
public class A {
  public void search(boolean[] searchList) {
    // searchList array is used to identify what options to search for in a given order
   // e.g. boolean [] searchList = new boolean [] {false, false, true, false};
    boolean searchL = false;
    boolean searchM = false;
    boolean searchK = false;
    boolean searchA = false;

    if(searchList[0] == true) searchL = true;
    if(searchList[1] == true) searchM = true;
    if(searchList[2] == true) searchK = true;
    if(searchList[3] == true) searchA = true;

    if(searchL == true) // write a query to search for all Ls
    if(searchM == true) // write a query to search for all Ms
    ...........
}

有没有办法可以简化这段代码?

@All : 很抱歉之前发布了一个错误的问题。我很困惑!

谢谢, 索尼

【问题讨论】:

  • 使用布尔值可以让它们全部为真。您需要查看这些布尔值是如何设置的,并改为设置单​​个字段,然后您可以使用开关。
  • 在您的实际应用程序中设置布尔值的是什么?

标签: java string conditional switch-statement


【解决方案1】:

我是枚举的忠实粉丝:

public class A {
  enum SearchType {
   L, M, A, K;
 }
  public void search(SearchType type) {

    switch (type) {
     case L: 
          System.out.println("Searching for L");
          break;
     case M:
          System.out.println("Searching for M");
          break;
     case A: 
          System.out.println("Searching for A");
          break;
     case K:
          System.out.println("Searching for K");
          break;
     default:
          System.out.println("what to do here?");
          // throw exception?
}

另请注意:您的场景一次允许多个搜索布尔值为真,我认为这不是您的目标,但如果是,我们可以稍微调整一下。

【讨论】:

  • @Nathan 被枚举打败了!我确实需要学习这个概念,比静态 int 更干净
  • 如果你能做到这一点,你可以做System.out.println("Searching for "+type);而不是开关;)
  • @Blundell 是的,如果我可以改变关于 java 的事情,那就是将枚举推回到语言的开头,许多库在类型安全方面可能会少一些。
  • 我个人希望看到枚举消失,支持迭代。 Jigsaw 项目是朝着正确方向迈出的一步(一直步履蹒跚)。无论 OSGi 是否胜过它,如果我们将 Java 模块化,那么我们可以谈论需要 X​​ 版本的 JVM 库。人们希望您可以选择没有 X 的版本。(或将 swing / awt 的东西合并到一个层次结构中)。
  • @Edwin: enum != Enumeration.
【解决方案2】:

您应该将您的状态转换为枚举。例如,您的搜索布尔值似乎是排他性的,所以我会这样做:

enum SearchOption {
  searchA, searchK, searchL, searchM
}

// then you can do 

SearchOption searchOption = searchA;

switch (searchOption) {
  case searchA: 
    System.out.println("I am searching for A");
    break;
  case searchK: 
    System.out.println("I am searching for K");
    break;
  case searchL: 
    System.out.println("I am searching for L");
    break;
  case searchM: 
    System.out.println("I am searching for M");
    break;    
}

如果您的状态不是排他性的,您应该尝试 build 以最初构建一组超级排他状态。

【讨论】:

  • Toader,你打字很快。我将删除我几乎相同的帖子。
  • @Edwin :)) 很抱歉 :)。我确实在某些时候训练过自己触摸打字:)。
  • 完全没有问题。在更好的日子里,我可以做到 65 wpm。仍然做噩梦,我在 Selectric 听力“b”“b”“b”空间前!
  • @Edwin :)) 是的 .. 确实如此 :(.
【解决方案3】:

像这样:?

public class A {
  public void search() {

    private static final int SEARCH_L = -1;
    private static final int SEARCH_M = 0;
    private static final int SEARCH_A = 1;
    private static final int SEARCH_K = 2;

int status;

switch(status){
 case SEARCH_L:
    System.out.println("I am searching for L");
  break;
 case SEARCH_M:
    System.out.println("I am searching for M");
  break;
 // Etc

 default:
    // Log error didn't hit a known status
   break;
}

}

【讨论】:

    【解决方案4】:

    为什么不使用 OOP?喜欢:

    public interface Seeker {
       void seek();
    }
    public class LSeeker implements Seeker {
       void seek() { System.out.println("Will search for L"); }
    }
    // ... More implementations of Seeker
    public class SeekDriver {
       void seek(Seeker seeker) { seeker.seek(); }
    }
    

    【讨论】:

    • 如何解决这个问题?程序仍然需要在某个时间点选择要实例化的 Seeker
    • @Dave Costa:是的,低级工厂将使用“switch”或“if”来创建实现。然而,似乎 OP 代码不关心对象的创建,而是关心某种算法。 OOP 更适合这里。
    • 它没有回答问题,但它解决了问题。有时人们只是想知道他们的问题的答案,但有时他们会因为被引导到更好的解决方案而受益更多。
    【解决方案5】:
    public class A {
    
        public enum SearchOption {
            SEARCH_L,
            SEARCH_M,
            SEARCH_A,
            SEARCH_K;
        }
        /**
         * Make them pass in an enum for your search.
         * Pros: type safe, can only use the selections you give
         * Cons: must add to the enum to add new types
         * @param option
         */
        public void enumSearch(SearchOption option) {
    
            switch(option) {
            case SEARCH_A:
                System.out.println("I am searching for A");
                break;
            case SEARCH_K:
                System.out.println("I am searching for K");
                break;
            case SEARCH_L:
                System.out.println("I am searching for L");
                break;
            case SEARCH_M:
                System.out.println("I am searching for M");
                break;
            }
        }
    
        /**
         * Use a primitive for your input
         * Pros: Gives you more options without updating the enum
         * Cons: Users could enter input you don't really want them to use
         * @param option
         */
        public void charSearch(char option) {
            switch(option) {
            case 'a':
            case 'A':
                System.out.println("I am searching for A");
                break;
            case 'k':
            case 'K':
                System.out.println("I am searching for K");
                break;
            case 'l':
            case 'L':
                System.out.println("I am searching for L");
                break;
            case 'm':
            case 'M':
                System.out.println("I am searching for M");
                break;
            }
        }
    
        /**
         * Use a primitive and don't even actually check it! Just run with it!
         * @param option
         */
        public void uncheckedSearch(char option) {
            System.out.println("I am searching for " + option);
        }
    }
    

    根据您的评论,这是我对该方法的更新示例 - 确保顶部的评论已更新!

    /**
     * Perform the search based on the options provided
     * The list should be in the order of L, M, A, K
     * @note update this comment as more search options are added
     * @param searchList the list of flags indicating what to search for
     */
    public void search(boolean[] searchList) {
    
        // as per docs, [0] denotes an L search:
        if(searchList[0]) 
            // write a query to search for all Ls
    
        // as per docs, [1] denotes an M search:
        if(searchList[1]) 
            // write a query to search for all Ms
    
        // as per docs, [2] denotes an A search:
        if(searchList[2]) 
            // write a query to search for all As
    
        // as per docs, [3] denotes a K search:
        if(searchList[3]) 
            // write a query to search for all Ks
    }
    

    最新想法:

    // Use the SearchOption enum from above
    Map<SearchOption, String> searches = new HashMap<SearchOption, String>();
    
    public List<SearchResult> search(List<SearchOption> options) {
        List<SearchResult> results = new LinkedList<SearchResult>();
        for(SearchOption option : options) {
            String query = searches.get(option);
            SearchResult result = MySearchService.executeQuery(query);
            results.add(result);
        }
        return results;
    
    }
    

    【讨论】:

    • 嗨!很抱歉给您带来麻烦,但我对自己的目标感到困惑。我编辑了我的问题。你能调查一下吗?谢谢!!!!
    • 我之前尝试过这段代码,但我想知道是否有使用 switch 的方法。如果这是最简单的方法,我会继续这样做..再次感谢!
    • 好吧,如果您希望能够同时搜索 K 和 L,那么除此之外别无他法。如果您知道一次只需要一个搜索,那么调整我上面的答案是更好的方法。
    • 是的,我应该可以同时搜索 K 和 L。再次感谢!
    • @sony 我在新想法中进行了编辑。显然,您需要提前使用您的查询填写 searches
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多