【问题标题】:How do I access a variable of one class in the function of another class?如何在另一个类的函数中访问一个类的变量?
【发布时间】:2012-05-01 02:20:05
【问题描述】:

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

【问题讨论】:

  • 不是作业:) 这是我的个人作业

标签: java class


【解决方案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

    }
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-28
      • 2023-04-07
      • 2020-11-24
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 2010-10-14
      相关资源
      最近更新 更多