Terminal Guy
Terminal Guy

Reputation: 188

Java: How to loop through an array and check that it matches a variable value?

I have an argument which is of type char. I want to check that this char is lower case, if this is true then I will make a boolean variable equal true, otherwise, make it equal false. I have created an array of chars:

String argumentStr = args[2];
char argument = argumentStr.charAt(0);
boolean acceptArgument;

char[] lowerCaseAlphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

Then I have tried two different solutions, but each is outside of the scope of my acceptArgument boolean.

First:

for (int i = 0; i < 27; i++) {
        if (argument == lowerCaseAlphabet[i]) {
            acceptArgument = true;
        } else {
            acceptArgument = false;
        }
    }

Second:

for (char letter: lowerCaseAlphabet) {
        if (argument == letter) {
            acceptArgument = true;
        } else {
            acceptArgument = false;
        }
    }

I understand why it won't work, because of the scope of the if statements compared with the acceptArgument boolean. But I don't know how to get around this. Please advise.

Upvotes: 0

Views: 2334

Answers (2)

The Scientific Method
The Scientific Method

Reputation: 2436

I understand why it won't work, because of the scope of the if statements compared with the acceptArgument boolean

No. the reason is not scope, it is because of at each iteration acceptArgument is getting either false or truebased on if condition until it finishs the whole loop because you did not use any break or what ever to get out of the loop when match found.

For example if argument = 'p', it will find match at letter='p', and therefore acceptArgument will be set to true. However, the loop advances to next letter q, sincep != q, acceptArgument will be set to false and continues like that. that is why it is not working what you expect.

see the correction below

to correct your code, make the following modification

First initialize;

boolean acceptArgument=false;

Second remove else it should be like this

for (char letter: lowerCaseAlphabet) {
    if (argument == letter) 
        acceptArgument = true;          
}

it works.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

You don't need an extra array for this. You can check if argument is lower case by comparing the result to Character.toLowerCase(char) like

char argument = argumentStr.charAt(0);
boolean acceptArgument = argument == Character.toLowerCase(argument);

or (as pointed out by @JBNizet) use Character.isLowerCase(char) like

boolean acceptArgument = Character.isLowerCase(argument);

If you also need to test that the character is a letter you can add an and for that like

boolean acceptArgument = Character.isLetter(argument) 
        && Character.isLowerCase(argument);

Upvotes: 1

Related Questions