javavariableslocal

Problem with scoped local variables and conditionals


I am trying to construct method which returns a boolean:

public boolean isStringValid(String s){
    boolean isValid;
    String temp = null;     
    // only combinations of 'A','B','C' are allowed
    for (int i = 0; i < s.length(); i++)
    {
        temp = s.substring(i, i+1);
        if (temp.equals("A")|temp.equals("B")|temp.equals("C")){
            isValid= true;
        }else{
            isValid= false;
        }
    }   
    return isValid;
}

But I get a compiler error saying "the local variable isValid may not have been initialized".

What I am trying to do is take a string and examine its every letter, if any letter other than A, B or C is found in the string, the isStringValid method should return a false. Only after every letter is checked and found to be either A,B or C can the method return true.

I guess I am having trouble figuring out the scope of the local variables. What is the appropriate way for the method to return from within the if/else blocks? If that is not possible, what would you recommend is the best way to design this?

Thank you in avdance Kindest regards


Solution

  • I agree with the answers that state that you should initialize the isValid boolean variable.

    However, you could do what you want with a regular expression

    /*
    * returns false if s contains a character different from 'a' 'b' or 'c' 
    */
    public boolean isStringValid(String s){
         return !Pattern.matches("($^|[^abc]+)",s);
    }
    

    [abc] means that you are checking if s contains the 'a','b' or 'c' character

    [^abc] means that you are checking if s contains a character that´s none of 'a','b' or 'c'.

    [^abc]+ means that you are checking if s contains at least one character that´s none of 'a','b' or 'c'.

    $^ Means empty strings