java中使用switch块代替多个if语句

发布于 2024-10-18 02:23:56 字数 768 浏览 6 评论 0原文

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:抱歉之前发布了错误的问题。我很困惑!

谢谢, 索尼

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
    ...........
}

Is there a way I can simplify this code ?

@All : Sorry for posting a wrong question before. I was confused!

Thanks,
Sony

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

煮酒 2024-10-25 02:23:56

我是枚举的忠实粉丝:

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?
}

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

I am a big fan of enums:

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?
}

note also: your scenario allowed more than one search boolean to be true at a time, I assumed that was not your goal, but if it is we can tweak this a bit.

泪是无色的血 2024-10-25 02:23:56

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

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

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

You should convert your state into an enum. For example your search booleans seem to be exclusive so i would do something like this:

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

If your states aren't exclusive you should try build to build a super set of exclusive states initially.

小兔几 2024-10-25 02:23:56

为什么不采用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(); }
}

Why don't employ OOP? Like:

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(); }
}
瞄了个咪的 2024-10-25 02:23:56
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;

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

As per your comment, here's my updated example of that method - make sure the comment at the top is updated!

/**
 * 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
}

Latest idea:

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

}
儭儭莪哋寶赑 2024-10-25 02:23:56

像这样: ?

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

}

Like this: ?

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

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文