简体   繁体   English

(JAVA)选项卡声明错误(在构造函数中使用类选项卡)

[英](JAVA) Tab declaration error ( using a class tab in constructor )

I have a problem with a declaration of tab in Java, I'm declaring a new array tab in a class and I want to use it in the constructor and then return the constructor's tab in a method, but I have problem with the tab declaration ( compiler error ). 我在Java中使用tab声明时遇到问题,我在类中声明了一个新的数组tab ,我想在构造函数中使用它,然后在方法中返回构造函数的tab ,但是tab声明有问题(编译器错误)。 What's wrong here ? 怎么了

class pascal5 {
int[] tab;
int prev1, prev2;

pascal5(int n) {
    tab[]=new int[n+1];

    for(int i = 0; i <= n; i++) {
        for(int k = 0; k <= i; k++) {
            if (k == 0) {
                tab[k] = 1;
                prev2 = 1;
            } else {
                prev1 = tab[k-1] + tab[k];
                tab[k-1] = prev2;
                prev2 = prev1;
            }
        }
    }
}

   int wspolczynnik(int m) {
   return tab[m];
  }

you cannot use the brackets [] after declaring the array just use the name of array to assign a new Array 您不能在声明数组后使用方括号[]来仅使用数组名称来分配新的数组

Replace this line tab[]=new int[n+1]; 替换此行tab[]=new int[n+1]; with tab = new int[n+1]; tab = new int[n+1];

Your problem is with the statement: 您的问题在于以下语句:

tab[] = new int[n+1];

Instead, use: 而是使用:

tab = new int[n+1];

You are initialising your tab in wrong way inside the constructor, 您在构造函数中以错误的方式初始化了tab

Do it like this, 像这样做,

tab = new int[n+1];

For more info on Arrays, check here . 有关数组的更多信息,请参见此处

You can also declare your array like this: 您也可以这样声明数组:

int[] tab = new int[3];
int[] tab = {1,2,3};
int[] tab = new int[]{1,2,3};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM