无法从类Stack1的参数构造函数初始化数组大小...但是如果我直接将整数值输入数组代码,则工作正常

问题描述

package the_JC;

public class Cls_01 {   
    
    public static void main(String[] args) {
        // Todo Auto-generated method stub
        Stack1 obj1 = new Stack1(20);
        for(int i = 1; i<=obj1.len; i++) {
            obj1.push(i*3+i);
        }
        for(int i=0; i < obj1.len; i++) {
            System.out.println(obj1.pop());
        }
        
    }

}
class Stack1{
    int len=0;
    Stack1(int num){
        len = num;
        System.out.println(len);
    }
    int[] stck = new int[len]; // this array is not accepting len as value from constructor above,taking len =0
    int pos = -1;
    
    void push(int value) {
        System.out.println(stck.length);
        if(pos==len-1) {
            System.out.println("Overflowed");
        } else {
            stck[++pos] = value;
            System.out.println("Pushed value :\t"+value);
        }
    }
    int pop(){
        if(pos<0) {
            System.out.println("Underflow");
            return 0;
        } else {
            return stck[pos--];
        }
    }
    
}

输出

Exception in thread "main" java.lang.Arrayindexoutofboundsexception: Index 0 out of bounds for length 0
    at the_JC/the_JC.Stack1.push(Cls_01.java:33)
    at the_JC/the_JC.Cls_01.main(Cls_01.java:10)**

解决方法

class Stack1{
    int len=0;
    int[] stck;
    int pos;
    Stack1(int num){
        len = num;
        stck = new int[len];
        pos = -1;
        System.out.println(len);
    }

    
    void push(int value) {
        System.out.println(stck.length);
        if(pos==len-1) {
            System.out.println("Overflowed");
        } else {
            stck[++pos] = value;
            System.out.println("Pushed value :\t"+value);
        }
    }
    int pop(){
        if(pos<0) {
            System.out.println("Underflow");
            return 0;
        } else {
            return stck[pos--];
        }
    }
    
}