2012-01-18 28 views
1

我想为大小为x的数组编写一个构造函数,其中x是main()中指定的参数。
我的类:可变大小的数组的构造函数

public class CharA 
{ 
    private char[] stack; 
    private int n = 0; 

    public void CharA (int max) 
    { 
    this.stack = new char[max]; 
    this.n = max; 
    } 

我的主要():

public class CharTest 
{ 
    public static void main (String args) 
    { 
    CharA stack1 = new CharA(100); 
    } 
} 

错误:

CharTest.java:5: cannot find symbol 
symbol : constructor CharA(int) 
location: class CharA 
    CharA stack1 = new CharA(100); 
       ^

有几个例子在这些地方同样的事情用一个int数组实现。为什么它不适用于这个char数组?

回答

6

删除void在你的“构造”:

public CharA (int max) { 
    // ... 
} 
+0

哦,上帝,我现在感到无比愚蠢。谢谢。 – Marv 2012-01-18 22:51:55

+2

@Marv:它发生在最好的:) – 2012-01-18 22:54:52

4

public void CharA (int max)替换为public CharA (int max),因为构造函数没有返回类型。

2

的构造方法,不应该有一个返回类型的定义中:

public CharA(int max) {...}