Keith
Keith

Reputation: 133

Variable not accessable

Im doing a bit of java home work and I seem to be having a small problem. The problem im having is the variable that Im trying to reference is showing that it is not initialized. However, I declared the variable earlier in the method and then had it initialized in a loop. When i try to access the variable when i make the charCount call a few lines later in the same method, the compiler complains that the variable still needs to be initialized. Can someone explain why this isnt working as i think it should.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class test {
    public int charCountHelper(File handle, Character x) throws IOException {
        int count = 0;
        String data;
        int index;
        Character[] contents;
        Scanner inputFile = new Scanner(handle);

        while(inputFile.hasNext()){
            data=inputFile.nextLine();
            index = data.length()-1;

            for(int i = 0; i< data.length(); i++){
                contents = new Character[data.length()] ;
                contents[i] = data.charAt(i);
            }

            count += charCount(contents,x,index);

        }

        inputFile.close();
        return count;

    }

public int charCount(Character[] content, Character x, int index) {


        if(index < 0){
            return 0; // this value represents the character count if the program reaches the beginning of the array and has not found a match.
        }
        if (content[index].equals(x)) {
            return 1 + charCount(content, x, index - 1);
        }
            return charCount(content, x, index - 1); // this is the value that gets returned to the original calling method.

    }
}

Upvotes: 0

Views: 32

Answers (1)

yole
yole

Reputation: 97128

In your code, contents will not be initialized if data.length() is equal to 0. Initializing contents in the loop is in any case not correct, because if you do it that way, it will only contain one character assigned during the latest initialization of the loop. Simply move the line initializing contents above the loop.

Upvotes: 3

Related Questions