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";
解决方案
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