For Each Loop Inside a If Statement?

I've been getting an "illegal start of expression" error when trying to compile this for loop inside a if statement in java. Does anyone have any idea why?

if(letter.equals(" ") || letter == null ||for(String a: array){ letter.equals(a);})
1

5 Answers

Try

if( letter == null || letter.equals(" ") ||  checkArray(array, letter))
{
    ...
}


boolean checkArray(String[] arryay, String letter)
{
     for(String a: array) 
           if(letter.equals(a)) 
                return true;

     return false;
}

Note: checking letter for null after you have already called equals() does not make too much sense; i've reordered those.

0

You cannot. Perhaps you should move the if statement into the for statement?

As rfausak said, a for statement does not return a boolean. You should have made that an answer by the way.

If you use a Set you could write:

if ( (letter.equals(" ")) || (letter == null) || (a.contains(letter)) ) {}

Well, that´s because you can not have a for loop within an if condition. It seems you want to see if the letter is within the array array; if so then you can do it with Apache commons-lang's ArrayUtils:

ArrayUtils.contains( array, letter );

This wont work because a for doesn't evaluate to a boolean. For readabilities sake you should extract that to a method anyway, good examples appear in other answers.

Other points, you should rejig your conditionals to not be susceptible to NullPointerExceptions

if (letter == null || " ".equals(letter) || arrayContains(array, letter)) {
        //...
}

If you are able to add additional libraries, there are some nice apache commons libraries to make this work easier, namely StringUtils in commons-lang and CollectionUtils in commons-collections.

You also may like to harden that input checking if it's possible to get Strings larger than one character, by using String#trim() after checking for null. Again, this would be a good candidate for an extracted method isBlank(String str).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest