如何在另一个类的函数中访问一个类的变量?

时间:2012-04-19 14:27:38

标签: java class

我正在使用 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..
    }
}

2 个答案:

答案 0 :(得分: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

    }
}

答案 1 :(得分:0)

您可以将变量文本作为函数

中的参数传递
public int alphabetOccurrence(char letter, String text){
    String text2 = text;
    // use text variable here...
}