java程序中堆栈实现的push()部分中的nullpointerexception

js4nwp54  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(284)

我的代码基本上是一个程序,用于检查是否可以使用有序序列1,2,3..,n来生成用户使用堆栈作为临时存储结构指定的序列排列。用户可以选择输入n和他希望看到的使用2种方法生成的排列;通过文本文件或直接在命令行中。因此,例如,如果用户输入5135442,n将被解释为第一个数字,即5,然后其余的数字是他想看是否有可能从123445开始生成的排列(注意123445是有序的,1在堆栈的顶部)。在这里你会有1被直接使用,然后2被存储在堆栈中,然后3被使用,然后4被存储在2的上面,然后5被使用,然后4被弹出,然后2被弹出来生成排列。我遇到的问题是,每当我尝试生成1 2 3的起始堆栈时,我的程序都会面临nullpointerexception。。。n。它指向这段代码的最后一行:

public static void main(String args[])
{
    int[] arr;
    arr = null;
       try
       {
        if(args[0].charAt(0) == '2') 
        {   
            try
            {   
                FileInputStream file = new FileInputStream(args[1]);
                arr = input(file);
            }
            catch (FileNotFoundException e)
            {
                System.out.println("File not found.");
                System.exit(0);
            }
        }
        else if (args[0].charAt(0) == '1')
        {   
            arr = input();
        }   
           else 
        {
            System.out.println("Please enter a valid input option.");
            System.exit(0);
        }
    }
    catch (ArrayIndexOutOfBoundsException e)
    {
        System.out.println("Please enter a valid input option."); 
        System.exit(0);
     }
    int x;
    x = arr.length;
    System.out.println(x);
    ArrayPerm start = new ArrayPerm(x);
    ArrayPerm temp = new ArrayPerm(x);
    for (int i = 0; i < x; i++)
    {
        *start.push(x - i);*        
    }

它还指出:

public void push(int j)
{
    top++;
    Stack[top] = j;
}

arrayperm类基本上是堆栈实现。我试过这样做:

public void push(Integer j)
{
    if (j == null)
    {
        throw new NullPointerException("NULL ELEMENT!");
    }
    else
    {
        top++;
        Stack[top] = j;
    }
}

但它仍然显示出例外。如果有人能给我指出正确的方向,我会非常感激的。我花了一个小时在代码中查找问题,但没有结果。所以,提前谢谢!
编辑:这就是类的定义方式,所以堆栈不应该初始化?

public class ArrayPerm
{
  private int[] Stack;
  private int top;
  public int size;

public ArrayPerm(int n)
{
    size = n;
    int[] Stack = new int[n];
    top = -1;
}
w8biq8rn

w8biq8rn1#

你在跟踪变量 Stack . 代替

int[] Stack = new int[n];

具有

stackArray = new int[n];
8oomwypt

8oomwypt2#

尚未初始化“stack”成员变量。

相关问题