简体   繁体   English

将数组从构造函数传递给方法?

[英]Passing an array from a constructor to a method?

When I try to run it I get this: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 I want to initialize the array in the constructor SimpleIntegerStack and use it later on in the methods that follow... 当我尝试运行它时,我得到以下信息:线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:0我想在构造函数SimpleIntegerStack中初始化该数组,并在以后的方法中使用它。

package datastructures.simple_integer_stack;

public class SimpleIntegerStack {
int maxSize;
private int stack[]=new int[maxSize];

public SimpleIntegerStack(int maxSize) {

    int stack[]= new int [maxSize];
}

public void push(int element) {
    int i=-1;
    boolean stop = false;

    do{
        if(stack[i]==0){
            stack[i]=element;
            stop=true;
        }
        i++;

    }while(stop=false && i<stack.length);

}

public void pop() {
    int i=0;

    while(stack[i]!=0 && i<stack.length){
        i++;
    }
    if(i!=0)
        stack[i] = 0;
}

public int top() {
    int stacktop=-1;
    int i=0;
    boolean empty = true;
    while(stack[i]!=0 && i<stack.length-1){
        i++;
        empty=false;
    }
    if(i==stack.length-1){
        if (stack[i+1]==0){
            empty=true;
        }
        else stacktop=stack[i+1];
    }
    if(empty=false)
        stacktop=stack[i-1];
    return stacktop;
}

} }

Remove "int" from the code below: 从下面的代码中删除“ int”:

public SimpleIntegerStack(int maxSize) {

    // dont do this:  int stack[]= new int [maxSize];
    stack = new int[maxSize];  
}

What you have done is to declare a local variable, stack in the constructor. 您要做的是声明一个局部变量,该变量stack在构造函数中。 This variable happens to have the same name as the instance variable. 该变量恰好具有与实例变量相同的名称。 When the constructor function completes, the local variable goes out of scope. 构造函数完成后,局部变量将超出范围。

Thus the instance variable, stack is not affected by calls to the constructor. 因此,实例变量stack不受构造函数调用的影响。

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

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