我有一个类Main(它有public static void main(String []args))和另一个类MyDocument。
Main 类中有一个变量text
,我想从MyDocument类中的函数alphabetOccurrence()访问它。我该怎么做呢?我不想将它用作静态变量。并且只能在函数中进行任何更改,其余代码应保持不变。
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..
}
}