我有一个主类(其具有公共静态无效的主要(字串[] args))和另一个类myDocument中 。
有一个可变text
存在于我想从一个函数alphabetOccurrence()存在于类myDocument中访问主类。 我该怎么做呢? 我不想把它作为一个静态变量。 和任何变化只能做到在功能,代码的其余部分应保持不变。
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..
}
}