-2

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

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;
    }
}

但它仍然显示异常。如果有人能指出我正确的方向,我将不胜感激。我花了一个小时在我的代码中寻找问题而没有结果。所以,提前谢谢!

编辑:这就是类的定义方式,所以不应该初始化 Stack?

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;
}
4

2 回答 2

1

您正在隐藏变量Stack。代替

int[] Stack = new int[n];

stackArray = new int[n];
于 2012-08-25T13:04:31.567 回答
0

您尚未初始化“堆栈”成员变量。

于 2012-08-25T12:32:12.110 回答