2012-04-19 201 views
0

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

这是功课? – Perception 2012-04-19 14:32:34

+0

不作业:)这是我的个人作品 – hakiko 2012-04-19 14:35:03

回答

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 

    } 
} 
+0

它的工作原理,非常感谢:) – hakiko 2012-04-19 14:42:15

0

你可以通过可变文本作为参数在函数

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

谢谢我的朋友:) – hakiko 2012-04-19 14:43:13

相关问题