RonaldN
RonaldN

Reputation: 127

How do I pas instances, created in a class method, to another method in the same class?

I've created this Class:

class File {
    public String path;
    public int numberOfLines = 0;
    public String[] fileContent;

    public File (String file_path) {
         path = file_path;
    }

    public BufferedReader openFile () throws IOException {
        FileReader ReadFile = new FileReader(path);
        BufferedReader ReadFilePerLine = new BufferedReader(ReadFile);
    }    
    public int countLines () {
        String line;

        while((line = ReadFilePerLine.readLine()) != null){
            numberOfLines++;
        }
        return numberOfLines;
    } 
    public String[] readLines () {
        String[] fileContent = new String[numberOfLines];
        for (int i=0; i < numberOfLines; i++){
            fileContent[i] = ReadFilePerLine.readLine();
        }
    }
}

How do I get the countLines() method to know of the existence of ReadFilePerLine and how do I get him to use it? (same for the numberOfLines variable)

Upvotes: 0

Views: 45

Answers (2)

msrd0
msrd0

Reputation: 8361

You should use method arguments for that, like this:

public int countLines (BufferedReader in) {
    String line;

    while((line = in.readLine()) != null){
        numberOfLines++;
    }
    return numberOfLines;
} 

Upvotes: 0

Eran
Eran

Reputation: 393771

BufferedReader ReadFilePerLine = new BufferedReader(ReadFile);

this is a local variable of the openFile() method, and therefore exists only within the scope of that method.

If you want it to be accessible to other methods, make it an instance variable (i.e. move BufferedReader ReadFilePerLine; to be outside the method).

Upvotes: 1

Related Questions