Reputation: 47
package default_package;
import java.util.Scanner;
public class Main_Class
{
public static void main(String[] args)
{
System.out.print("Number of Input NFA States: ");
Scanner s=new Scanner(System.in);
int numberOfStates=s.nextInt();
State[] state=new State[numberOfStates];
for(int i=0;i<numberOfStates;i++)
{
System.out.println("state"+i+" Created.");
}
System.out.println("\nState0 is starting point.\n");
for(int i=0;i<numberOfStates;i++)
{/////////0,1 linking///////////
System.out.print("state"+i+"'s 0 is headed to: ");
state[i].link0=state[s.nextInt()];//THIS PART
System.out.print("state"+i+"'s 1 is headed to: ");
state[i].link1=state[s.nextInt()];
}
for(int i=0;i<numberOfStates;i++)
{////////epsilon linking//////////
System.out.print("Number of epsilon move for State"+i+":");
int j=s.nextInt();
if(j>0)
{
state[i].epsilon(j);
for(int i1=0;i1<j;i1++)
{
System.out.print("State"+i+"'s epsilon move "+i1+": ");
state[i].linke[i1]=state[s.nextInt()];
}
}
}
System.out.println("Done");
}
}
package default_package;
public class State
{
State link0;
State link1;
State[] linke;
public void epsilon(int a)
{
linke=new State[a];
}
}
As you can see, what i'm trying to do is get an NFA and translate it to DFA.
But i keep get NullPointException where i marked as "THIS PART" in the code.
To me, this method seems pretty same as creating ADTs through external Node Class but this code doesn't work.
I tried changing variable names and etc but couldn't find specific reason why this is not working.
Anybody with some wise tips?
Upvotes: 0
Views: 45
Reputation: 533530
If you used you debugger you would see that state[i]
is null
before you didn't set it to anything. You created an array of references, but you didn't point them to anything.
Try adding
State[] state=new State[numberOfStates];
for(int i=0;i<numberOfStates;i++)
{
// need to actually create each object, not just print that you did it.
state[i] = new State(/* any args needed */);
System.out.println("state"+i+" Created.");
}
Upvotes: 1
Reputation: 838
First of all your array is initialized but empty. second, are you trying to get an input directly into the expression of an array?
state[i].link0=state[s.nextInt()];//THIS PART
Have you tried this?
int headedTo = s.nextInt();
state[i].link0=state[headedTo];
This happens because state[i].link0
is trying to access a value inside the array, but that value is null because you are trying to get it before you can make the input, not sure it will work after you fill the array.
Upvotes: 0