0

I'm having a class Main (which has public static void main(String []args))and another class MyDocument.

There is a variable text present in the Main class which I want to access from a function alphabetOccurrence() present in the MyDocument class. How do I do this? I don't want to use it as a static variable. And any changes can be done only in the function, rest of the code should be untouched.

import java.util.*;

class Main {
    public static void main(String[] args) {
        MyDocument document = null;
        String text;
        text = "good morning. Good morning Alexander. How many people are there in your country? Do all of them have big houses, big cars? Do all of them eat good food?";
        char letter = 'd';
        document = new MyDocument();
        document.setDocumentText(text);
        System.out.println("Letter " + letter + " has occured "
                + document.alphabetOccurrence(letter) + " times");
    }
}

class MyDocument {
    private ArrayList<Character> document = new ArrayList();

    public MyDocument() {
    }

    void setDocumentText(String s) {
        for (int i = 0; i < s.length(); i++)
            document.add(s.charAt(i));
    }

    ArrayList getDocumentText() {
        return this.document;
    }

    public int alphabetOccurrence(char letter) {
        // use text variable here..
    }
}
Kevin Welker
  • 7,719
  • 1
  • 40
  • 56
hakiko
  • 27
  • 4

2 Answers2

1

You should change your MyDocument class to add new String field to hold text:

import java.util.ArrayList;

class MyDocument {

    private String text;
    private ArrayList<Character> document = new ArrayList();

    public MyDocument() {
    }

    void setDocumentText(String s) {
        this.text = text;
        for (int i = 0; i < s.length(); i++)
            document.add(s.charAt(i));
    }

    ArrayList<Character> getDocumentText() {
        return this.document;
    }

    public int alphabetOccurrence(char letter) {

        this.text; //do something

    }
}
Pau Kiat Wee
  • 9,485
  • 42
  • 40
0

you could pass variable text as a parameter in your function

public int alphabetOccurrence(char letter, String text){
    String text2 = text;
    // use text variable here...
}
Matthias
  • 7,432
  • 6
  • 55
  • 88
Evans Kakpovi
  • 312
  • 1
  • 5
  • 12