java.lang.ArrayIndexOutOfBoundsException error
Hi,
I've been trying to figure out how to get rid of this "java.lang.ArrayIndexOutOfBoundsException" error and have had no luck. Anyone have any suggestions?
Exception in thread "main" java.lang.ArrayIndexOutOf Bounds Exception: 0 at Josephus.main(Josephus.java:39)
The error is with:
int M = Integer.parseInt(args[0]);
publicclass Josephus{
privatestaticclass Node{
int value;
Node next;
}
// create a circular linked list of 1..N and return reference to last node
publicstatic Node create(int N){
Node last =new Node();
Node first = last;
last.value = N;
for (int i = N-1; i >= 1; i--){
Node x =new Node();
x.value = i;
x.next = first;
first= x;
}
last.next = first;
return last;
}
// count number of nodes in a circular linked list
publicstaticint count(Node first){
int n = 0;
Node x = first;
do{
x = x.next;
n++;
}while (x != first);
return n;
}
publicstaticvoid main(String[] args){
int M = Integer.parseInt(args[0]);// eliminate every Mth person
int N = Integer.parseInt(args[1]);// number of people
Node x = create(N);
System.out.println("count = " + count(x));
// delete every Mth person
while (x != x.next){
// skip M-1 positions
for (int i = 1; i < M; i++)
x = x.next;
System.out.print(x.next.value +" ");
// kill the Mth one
x.next = x.next.next;
}
// print survivor

