0

我有一个类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..
    }
}
4

2 回答 2

1

您应该更改您的MyDocument课程以添加String要保存的新字段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

    }
}
于 2012-04-19T14:31:17.677 回答
0

您可以在函数中将变量文本作为参数传递

public int alphabetOccurrence(char letter, String text){
    String text2 = text;
    // use text variable here...
}
于 2012-04-19T14:36:35.123 回答