如何访问一个类的变量在另一个类的功能?(How do I access a variable of

2019-10-28 12:54发布

我有一个类(其具有公共静态无效的主要(字串[] 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..
    }
}

Answer 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

    }
}


Answer 2:

你可以通过可变文本在您的函数中的参数

public int alphabetOccurrence(char letter, String text){
    String text2 = text;
    // use text variable here...
}


文章来源: How do I access a variable of one class in the function of another class?
标签: java class