Replacing if statement with for loop (Java)

廉价感情. 提交于 2019-12-12 14:37:10

问题


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

回答1:


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

For more read the this tutorial Java Regex - Tutorial




回答2:


You could create an array of consonants (maybe as a static constant of your class), and use a function doing the work, something along the lines of (pseudo code here)

boolean hasConsonants(String userInput) {
    for (String consonant : consonants)
        if (userInput.contains(consonant)
            return true;
    return false;
}

Then you would simple call

if (hasConsonants(userInput))
    results += "The input contains consonants";
else
    results += "The input contains no consonants";

P.S. probably better to have your consonants array to be a char[] and use char instead of String in the for each loop




回答3:


To use a for loop, you could do something like the following:

for (char c = 'b'; c <= 'z'; c++) {
    if (c == 'e' || c == 'i' || c == 'o' || c == 'u')
        continue;
    if (userInput.contains(String.valueOf(c))) {
        return "The input contains consonants";
    }
}
return "The input contains no consonants";



回答4:


Why not just do it like this:

private String[] mCharacters = new String[] { "a", "b", "c" };

public boolean hasSelectedCharacters(String str) {
    for (final String c : mCharacters) {
        if (str.contains(c)) {
            return true;
        }
    }
    return false;
}

If the input string contains any of the listed strings, it returns true, otherwise false. Identical to your long if, but more readable.




回答5:


boolean containsConsonant = 
    Pattern.compile("[bcdfghjklmnpqrstvwxyz]").matcher(userInput).find();



回答6:


char[] consonants = "bcdfghkjlmnpqrstvwxyz".toCharArray();
results = "The input contains no consonants";

for (int i = 0; i < consonants.length; i++)
    if (userinput.contains(String.valueOf(consonants[i])))
        results = "The input contains consonants";



回答7:


Why not something like:

if(java.util.regex.Pattern.compile("(?i)[b-df-hj-np-tv-z]").matcher(line).find())
    System.out.println("Contains consonants");



回答8:


Here's how I'd write this as a loop (I'm assuming that your string is already lowercased):

public static boolean containsConsonants(String s) {
    for (char c : "bcdfghjklmnpqrstvwxyz".toCharArray())
        if (s.indexOf(c) >= 0) return true;
    return false;
}

Here's another way, using a regular expression:

private static final Pattern consonantPattern =
    Pattern.compile("[a-z&&[^aeiou]]");
public static boolean containsConsonants(String s) {
    return consonantPattern.matcher(s).find();
}



回答9:


It will be more efficient and readable

if(Pattern.matches("[b-df-hj-np-tv-z]+",userInput)){  
    ----code----
}
else{
    ----other code----  
}



回答10:


Use regex expressions, eg:

if (userInput.matches (".*[bcdfghjklmnpqrstvwx]+.*"))
    results += "has consonants";
else
    results += "no consonants";

If you can ensure that no symbols will be used, then a simpler version would be:

if (!userInput.matches (".*[aeiou]+.*"))
    results += "has consonants";
else
    results += "no consonants";

Tweak to suit for case sensitivity.



来源:https://stackoverflow.com/questions/22054028/replacing-if-statement-with-for-loop-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!