用for循环替换if语句(Java) [英] Replacing if statement with for loop (Java)

查看:331
本文介绍了用for循环替换if语句(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一个项目,收到的评论之一是我的if语句太长.我同意这一点,但是我仍然对如何用建议的for循环替换它感到困惑.这一直让我发疯.该项目旨在分析句子中的辅音,并报告其中的辅音.这是我使用的代码.此项目已被标记,因此更多的是我的错误在哪里/可以在何处改进的问题".

I was working on a project and one of the comments that I received was that my if statement was too long. I agree with this but I'm still confused how to replace it with a for loop that was suggested. It has been driving me crazy. The project was to analyse the consonants in a sentence and report back if they are in it. Here is my code that I used. The project has been since marked so this is more of a "where is my mistake/ where can this be improved question".

if ((userInput.contains("b"))||(userInput.contains("c"))||(userInput.contains("d"))||
    (userInput.contains("f"))||(userInput.contains("g"))||(userInput.contains("h"))||
    (userInput.contains("j"))||(userInput.contains("k"))||(userInput.contains("l"))||
    (userInput.contains("m"))||(userInput.contains("n"))||(userInput.contains("p"))||
    (userInput.contains("q"))||(userInput.contains("r"))||(userInput.contains("s"))||
    (userInput.contains("t"))||(userInput.contains("v"))||(userInput.contains("w"))||
    (userInput.contains("x"))||(userInput.contains("y"))||(userInput.contains("z")))
        //checking for consonants
        results += "The input contains consonants";
else 
    results += "The input contains no consonants";

推荐答案

好,是时候学习正则表达式或RegEx.这样您的if语句将是:

Ok, time to learn Regular Expression or RegEx. So that the you if statement would be:

if (userInput.matches(".*[bcdfghjklmnpqrstvwxyz].*"))
   results += "The input contains consonants";
else 
   results += "The input contains no consonants";

有关更多信息,请阅读本教程 Java Regex-教程

For more read the this tutorial Java Regex - Tutorial

这篇关于用for循环替换if语句(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆