2012-04-19 205 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

相關問題