如何从其他类调用ArrayList?

时间:2019-04-07 16:46:29

标签: java arraylist

在方法getNumberOfMoves()中,我想调用在主方法中创建的堆栈“至”和“从”,因为我想计算元素在堆栈之间移动的次数。

我想检查堆栈“ to”是否为空,在这种情况下,执行了0次移动,如果已满,则完成了一定数量的移动(2 ^ n)-1。但是我在调​​用有问题的堆栈时遇到了麻烦,既不接受任何变量,也不接受“ to”或“ myStack”。

public class StackPlay {

    public static long getNumberOfMoves() {
        //This is were I get problems!
    }

    public static void move(myStack from, myStack to, myStack help, int n) {
        help.push(from.pop());
        to.push(help.pop());
    }

    public static void main(String[] args) {
        int size = 3;
        myStack from = new myStack(size);
        myStack to = new myStack();
        myStack help = new myStack();
        System.out.println("Start state");
        System.out.println("   From: " + from);
        System.out.println("   To:   " + to);
        System.out.println("   Help: " + help);
        System.out.println("   Number of moves: " + getNumberOfMoves());
        move(from, to, help, size);
        System.out.println("End state");
        System.out.println("   From: " + from);
        System.out.println("   To:   " + to);
        System.out.println("   Help: " + help);
        System.out.println("   Number of moves: " + getNumberOfMoves());
    }
}

下面是创建堆栈的类:

public class myStack {

    private ArrayList<Integer> specStack;

    public myStack() {
        specStack = new ArrayList<Integer>();
    }

    public myStack(int n) {
        this.specStack = new ArrayList<Integer>(n);
        int i;
        for (i=0; i<n; i++) {
            specStack.add(i, n-i);
        }
    }

    public void push(int x) { 
        if (specStack.size() == 0) {
            specStack.add(x);
        } else if (x > specStack.get(specStack.size() -1)) {
            throw new RuntimeException("Number too high");
        } else {
            specStack.add(x);
        }
    }

    public int pop() {
        if (specStack.size() == 0) {
          throw new RuntimeException("Empty stack");
        } else {
            int length = specStack.size() -1;
            int topEl = specStack.get(length);
            specStack.remove(length);
            return topEl;
        }
    }

    public String toString() {
        String arrList = "[";
        int i;
        for (i = 0; i < specStack.size(); i++) { 
            if (i == specStack.size() -1) {
                arrList = arrList + specStack.get(i);
            } else {
                arrList = arrList + specStack.get(i) + ",";
            }
        }
        arrList = arrList + "]";
        return arrList;
    }
}

0 个答案:

没有答案