后进先出 (LIFO) 抽象数据类型和数据结构.也许堆栈最常见的用途是存储


MyStack()
{
    Vector<Integer> v=new Vector<Integer>(10,2);
}
void push(int n)
{
    v.addElement(n);
}
void pop()
{
    if(v.isEmpty())
        System.out.println("Stack underflow!");
    else
        System.out.println(v.elementAt(0));
}
void display()
{
    for(int i=0;i<v.size();i++)
        System.out.print(v.elementAt(i) +" ");
}
}
class StackDemo
{
    public static void main(String args[])
    {
        Scanner in=new Scanner(System.in);
        MyStack s=new MyStack();
        int option=0;
        do
        {
            System.out.println("1: Pushn2:Popn3:Displayn4:Quit");
            System.out.println("Enter your option: ");
            option=in.nextInt();
            switch(option)
            {
                case 1:
                {
                System.out.println("Enter an integer:");
                int n=in.nextInt();
                s.push(n);break;
                }
                case 2:s.pop();break;
                case 3:s.display();break;
            }
        }
    while(option!=4);
    }
}

抛出错误:找不到变量 v。任何帮助将不胜感激。谢谢。

看起来

v是在构造函数中本地创建的,而不是作为类的成员创建的。

尝试将v定义为类成员,然后简单地在构造函数中分配它。

class MyStack {
    Vector<Integer> v;
    public MyStack() {
        v = new Vector<Integer>(10,2);
    }
}

或者只是在定义它时分配它:

class MyStack {
    Vector<Integer> v = new Vector<Integer>(10,2);
}

查看有关类成员的 Java 教程。

相关内容

最新更新