My code is basically a program to check whether it is possible to use the ordered sequence 1,2,3..,n to generate a permutation of this sequence as specified by the user using a stack as temporary storage structure. The user has the option of entering n and the permutation he’d like to see generated using 2 methods; either through a text file or directly in the command line.
So, for example if the user enters 5 1 3 5 4 2, the n would be interpreted as the first number, i.e. 5 and then the rest of the digits is the permutation he’d like to see if it’s possible to generate starting from 1 2 3 4 5 (Note that 1 2 3 4 5 is ordered and 1 is at the top of that stack). Here you’d have 1 being used directly, then 2 being stored in a stack, then 3 being used, then 4 stored on top of 2, then 5 being used, then 4 popped out followed by 2 being popped to generate the permutation.
The problem I’m having is my program faces a NullPointerException whenever I try to generate the starting stack of 1 2 3 … n. It points to the last line of this block of code:
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);*
}
And it also points to:
public void push(int j)
{
top++;
Stack[top] = j;
}
The ArrayPerm class is basically the stack implementation.
I tried doing this:
public void push(Integer j)
{
if (j == null)
{
throw new NullPointerException("NULL ELEMENT!");
}
else
{
top++;
Stack[top] = j;
}
}
But it’s still showing the exception. If anyone could point me in the right direction I’d really appreciate it. I’ve spent an hour looking for the problem in my code without result.
So, thanks in advance!
EDIT: This is how the class is defined, so Stack shouldn’t be initialized?
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;
}
You’re shadowing the variable
Stack. Replacewith