在Java中访问对象成员

时间:2014-08-18 20:43:31

标签: java object global

我对如何创建我正在定义的对象的实例以及如何访问其字段感到困惑。完整代码如下。我的类叫做compressedString,我做了一个构造函数:

public CompressString(char let, int appears){
    char letter = let;
    int  freq = appears;
}

稍后在我的代码中,我尝试从链表中删除CompressString对象后访问字段letter和freq,但那是我遇到麻烦的地方。

    CompressString tempNode;

    for(int j = 0; j<compressedString.length; j+=2){
        tempNode = list.pop();
        array[j] = tempNode.letter;
        array[j+1] = tempNode.freq;
    }

Eclipse给了我一个错误,直到我为letter和freq创建了类级变量。为什么我需要类级变量来访问这些字段,每次从这些对象的链表中弹出一个节点时,我是否只是覆盖它们?

以下是完整代码:

public class CompressString{

private char freq = 0;
private char letter;


public CompressString(char let, int appears){
    char letter = let;
    int  freq = appears;
}

public static void main(String[] argv){
    String str = "aaabbbccc";
    String str1 = "abc";
    String str2 = "abbbcccaaacccbbbccccc";

    System.out.println(compress(str));
    System.out.println(compress(str1));
    System.out.println(compress(str2));
}


private static String compress(String str){
    LinkedList<CompressString> list = new LinkedList();
    char[] array = str.toCharArray();
    char temp = array[0];
    int i = 1;
    int counter = 1;
    while(i<array.length){
        if(temp != array[i]){
            CompressString node = new CompressString(temp, counter);
            list.add(node);
        }
        temp = array[i];
        counter = 1;
        i++;
    }

    char[] compressedString = new char[list.size()*2];
    CompressString tempNode;
    for(int j = 0; j<compressedString.length; j+=2){
        tempNode = list.pop();
        compressedString[j] = tempNode.letter;
        compressedString[j+1] = tempNode.freq;
    }

    str = Arrays.toString(compressedString);
    return str;

}
}

现在它只打印空白

1 个答案:

答案 0 :(得分:3)

您的构造函数不是设置字段值,而是设置本地值。此

public CompressString(char let, int appears){
  char letter = let;
  int  freq = appears;
}

应该是

public CompressString(char let, int appears){
  this.letter = let;
  this.freq = appears;
}

另外,请确保将freqletter标记为public,或者定义getFreq()getLetter()等方法,如果您还没有