Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中,除了遵循if-else梯形图外,还有什么更好的选择?_Java_String_If Statement_Optimization - Fatal编程技术网

在java中,除了遵循if-else梯形图外,还有什么更好的选择?

在java中,除了遵循if-else梯形图外,还有什么更好的选择?,java,string,if-statement,optimization,Java,String,If Statement,Optimization,情况:我正在检查文件名,文件名存储在名为str的变量中,根据if语句中检查的条件,我正在设置名为mailType的变量的值 if(str.contains("template")) { if(str.contains("unsupported")) mailType="unsupported"; else if(str.

情况:我正在检查文件名,文件名存储在名为
str
变量中,根据
if
语句中检查的条件,我正在设置名为
mailType
的变量的值

if(str.contains("template"))
        {                   
          if(str.contains("unsupported"))
              mailType="unsupported";      
              else
                  if(str.contains("final_result"))                
                      mailType="final_result";            
                  else
                      if(str.contains("process_success"))
                          mailType="Process Success"; 
                      else
                          if(str.contains("receive"))                         
                              mailType="Receive";                         
                          else
                          if(str.contains("sen"))
                              mailType="sent"; 
                          else
                              if(str.contains("welcome"))
                                  mailType="welcome";
                              else
                                  if(str.contains("manual"))
                                     mailType="Manual";                    
        }       
        else                
if(str.contains("properties"))
        {

          if(str.contains("unsupported"))
              mailType="unsupported";      
              else
                  if(str.contains("final_result"))                
                      mailType="final_result";            
                  else
                      if(str.contains("process_success"))
                          mailType="Process Success"; 
                      else
                          if(str.contains("receive"))                         
                              mailType="Receive";                         
                          else
                          if(str.contains("sen"))
                              mailType="sent"; 
                          else
                              if(str.contains("welcome"))
                                  mailType="welcome";
                              else
                                  if(str.contains("manual"))
                                     mailType="Manual";

        }
问题:在java中,有没有更好的方法来缩短我的代码并对内存友好?

使用
LinkedHashMap

然后以相同的方式迭代键:

for (Map.Entry<String, LinkedHashMap<String, String>> outerEntry : outerMapping.entrySet()) {
  if (str.contains(outerEntry.getKey()) {
    // Apply the iteration above, using outerEntry.getValue().
  }
}
for(Map.Entry outerEntry:outerMapping.entrySet()){
if(str.contains(outerEntry.getKey()){
//使用outerEntry.getValue()应用上面的迭代。
}
}

首先,如果使用
else if
而不是简单的
else
,缩进会更少

if(str.contains("unsupported"))
          mailType="unsupported";      
else if(str.contains("final_result"))                
          mailType="final_result";            
else if(str.contains("process_success"))
          mailType="Process Success"; 
else if(str.contains("receive"))                         
          mailType="Receive";                         
else if(str.contains("sen"))
          mailType="sent"; 
else if(str.contains("welcome"))
          mailType="welcome";
else if(str.contains("manual"))
          mailType="Manual";        
在您的特殊情况下,我建议尝试使用正则表达式来简化您的工作:

Pattern p = Pattern.compile("(unsupported|final_result|welcome)");
Matcher m = p.matcher(str);
if (m.matches()) {
    mailType = m.group(1);
}
你说你觉得(我也会这么做)太复杂了。他建议的
else if
可能是你的一个选择:

if (str.contains("template")) {
    if (str.contains("unsupported"))
        mailType = "unsupported";
    else if (str.contains("final_result"))
        mailType = "final_result";
    else if (str.contains("process_success"))
        mailType = "Process Success";
    else if (str.contains("receive"))
        mailType = "Receive";
    else if (str.contains("sen"))
        mailType = "sent";
    else if (str.contains("welcome"))
        mailType = "welcome";
    else if (str.contains("manual"))
        mailType = "Manual";
} else if (str.contains("properties")) {
    if (str.contains("unsupported"))
        mailType = "unsupported";
    else if (str.contains("final_result"))
        mailType = "final_result";
    else if (str.contains("process_success"))
        mailType = "Process Success";
    else if (str.contains("receive"))
        mailType = "Receive";
    else if (str.contains("sen"))
        mailType = "sent";
    else if (str.contains("welcome"))
        mailType = "welcome";
    else if (str.contains("manual"))
        mailType = "Manual";
}
或者更好的是,通过一致地使用{}:

if (str.contains("template")) {
    if (str.contains("unsupported")) {
        mailType = "unsupported";
    } else if (str.contains("final_result")) {
        mailType = "final_result";
    } else if (str.contains("process_success")) {
        mailType = "Process Success";
    } else if (str.contains("receive")) {
        mailType = "Receive";
    } else if (str.contains("sen")) {
        mailType = "sent";
    } else if (str.contains("welcome")) {
        mailType = "welcome";
    } else if (str.contains("manual")) {
        mailType = "Manual";
    }
} else if (str.contains("properties")) {
    if (str.contains("unsupported")) {
        mailType = "unsupported";
    } else if (str.contains("final_result")) { 
        mailType = "final_result";
    } else if (str.contains("process_success")) {
        mailType = "Process Success";
    } else if (str.contains("receive")) {
        mailType = "Receive";
    } else if (str.contains("sen")) {
        mailType = "sent";
    } else if (str.contains("welcome")) {
        mailType = "welcome";
    } else if (str.contains("manual")) { 
        mailType = "Manual";
    }
}
试试这个

static String containsAndValue(Collection<String> collection, String oldValue, String... strings) {
    if (strings.length % 2 != 0)
        throw new IllegalArgumentException("strings");
    for (int i = 0; i < strings.length; i += 2)
        if (collection.contains(strings[i]))
            return strings[i + 1];
    return oldValue;
}
这不那么复杂吗

public enum MailType {
    UNSUPPORTED("unsupported", "unsupported"),
    FINAL_RESULT("final_result", "final_result"),
    PROCESS_SUCCESS("process_success", "Process Success"),
    RECEIVE("receive", "Receive"),
    SENT("sen", "sent"),
    WELCOME("welcome", "welcome"),
    MANUAL("manual", "Manual");

    private final String query;
    private final String value;

    MailType(String query, String value) {
        this.query = query;
        this.value = value;
    }

    public static String find(String text){
        for(MailType mailType: values()){
            if(text.contains(mailType.query)) {
                return mailType.value;
            }
        }
        return null;
    }
}
然后像这样使用它:

String mailType = MailType.find(str);

如果使用
if-else
而不是
else
(不带大括号),则代码的可读性会更好然后缩进后续的块。只是提出Andy的观点:或者更好@T.J.Crowder谢谢你添加这些!@T.J.Crowder有趣的是,没有正确格式的阶梯,答案变得很明显。无意冒犯,但我发现这种方法有点复杂,因为我是初学者,你能推荐其他方法吗?而且这种方法需要你选择的方法取决于你想要优化什么。这只是一种方法;我可以看到为什么你会认为它是初学者的复杂。如果你想动态地指定映射(例如,在外部配置中),这是非常好的;正如他们所说的,YMMV:@varunsinghal:以上内容只会占用少量内存,无需担心。它也很容易维护,而且一点也不复杂。FWIW,这就是我要做的,或者类似的事情。正则表达式方法不太管用-一些
邮件类型与匹配的邮件类型不一样(例如
process\u success
=>
process success
)。是的,但至少它可以帮助删除一些if语句。在字符串处理的情况下,我尽量使用正则表达式,因为它是合适的工具。“我尽量使用正则表达式,因为它是合适的工具”你显然从未听说过引号:),我认为它并没有真正的帮助-然后你只需创建一个从“你发现的正则表达式”到相应值的映射。然后你基本上回到我的解决方案。
static String containsAndValue(Collection<String> collection, String oldValue, String... strings) {
    if (strings.length % 2 != 0)
        throw new IllegalArgumentException("strings");
    for (int i = 0; i < strings.length; i += 2)
        if (collection.contains(strings[i]))
            return strings[i + 1];
    return oldValue;
}
if (str.contains("template")) {
    mailType = containsAndValue(str, mailType,
        "unsupported", "unsupported",
        "final_result", "final_result",
        "process_success", "Process Success",
        "receive", "Receive",
        "sen", "sent",
        "welcome", "welcome",
        "manual", "Manual");
} else if (str.contains("properties")) {
    mailType = containsAndValue(str, mailType,
        "unsupported", "unsupported",
        "final_result", "final_result",
        "process_success", "Process Success",
        "receive", "Receive",
        "sen", "sent",
        "welcome", "welcome",
        "manual", "Manual");
}
public enum MailType {
    UNSUPPORTED("unsupported", "unsupported"),
    FINAL_RESULT("final_result", "final_result"),
    PROCESS_SUCCESS("process_success", "Process Success"),
    RECEIVE("receive", "Receive"),
    SENT("sen", "sent"),
    WELCOME("welcome", "welcome"),
    MANUAL("manual", "Manual");

    private final String query;
    private final String value;

    MailType(String query, String value) {
        this.query = query;
        this.value = value;
    }

    public static String find(String text){
        for(MailType mailType: values()){
            if(text.contains(mailType.query)) {
                return mailType.value;
            }
        }
        return null;
    }
}
String mailType = MailType.find(str);