Constructor for array of variable size

送分小仙女□ 提交于 2019-12-13 04:03:53

问题


I want to code a constructor for an array of size x with x being a parameter speciified in main().
My class:

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

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

My main():

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

The error:

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

There are several examples here where the same thing is done with an int array. Why doesn't it work for this char array?


回答1:


remove void in your "constructor":

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



回答2:


Replace public void CharA (int max) with public CharA (int max), because constructors don't have a return type.




回答3:


The constructor method should not have a return type in its definition:

public CharA(int max) {...}


来源:https://stackoverflow.com/questions/8918660/constructor-for-array-of-variable-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!