Skip to content
Advertisement

Knight’s Tour random move picker not working

I am working on randomizing which move my knight takes in my knight’s tour code. For some reason though, my switch statement always goes to default, instead of executing a possible move. I know my possible moves methods work because I have separately ran firstMoveChoice() on it’s own and it worked. So I know the problem is with my random move picker, but I can’t seem to figure it out.

Thanks for your help and time in advance! It is really much appreciated as I have looked this problem over and cannot find the answer.

JavaScript

Here is the result of the above code:

JavaScript

Here is my Main method:

JavaScript

Here is my ChessBoard class:

JavaScript

Here is firstMoveChoice()

JavaScript

Here is thirdMoveChoice(): It is practically the same as all the others, except for the change in numbers for the different moves.

JavaScript

Advertisement

Answer

It’s because random.nextInt() return a value between -2,147,483,648 and 2,147,483,647

you should use the random.nextInt(int n) that return a value between 0 inclusive and n exclusive

so replace

JavaScript

by

JavaScript

Also, you should assign new Random() to a field that would be reused.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement