簡體   English   中英

如何在另一個類的函數中訪問一個類的變量?

[英]How do I access a variable of one class in the function of another class?

我有一個Main類(具有公共靜態void main(String [] args) )和另一個類MyDocument

我要從MyDocument類中存在的函子AlphabetOccurrence()訪問Main類中存在的可變text 我該怎么做呢? 我不想將其用作靜態變量。 而且任何更改只能在函數中進行,其余代碼應保持不變。

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..
    }
}

您應該更改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

    }
}

您可以在函數中傳遞變量文本作為參數

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM