目前正在为游戏拼图和龙工作,并继续遇到这个我无法创建有效个人的问题,因为我无法创建有效的孩子。问题总是回到个人试图找到2d数组位置的位置,并在Array Traverse函数中返回空指针异常。
public class Individual {
static int MoveLength = 5;
int fitness = 0;
boolean Feasibility = true;
ArrayList<Integer> Move = new ArrayList();
public int[] position = new int[2];
char[][] PuzzleMatrix;
public void GenerateIndividual(){
PositionRandomizer();
RandomMoves();
MoveFollower();
// PrintMatrix(PuzzleMatrix);
if(this.Feasibility == false){
GenerateIndividual();
}
System.out.println("sucess");
}
public Individual(char[][] PuzzleMatrix){
PuzzleMatrix = this.PuzzleMatrix;
}
public void MoveFollower(){
for(int x = 0; x < Move.size(); x++){
ArrayTraverse(Move.get(x));
}
}
public int randomnumbergenerator(){
int[] myArray = {0,1,2,3};
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];
}
public void PositionRandomizer(){
/*
http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range
random position value
*/
Random ran = new Random();
int random = ran.nextInt(7);
Random ran2 = new Random();
int random2 = ran2.nextInt(7);
position[0] = random;
position[1] = random2;
}
public void RandomMoves(){
for(int x = 0; x < MoveLength; x++){
int randomMove = randomnumbergenerator();
Move.add(randomMove);
}
}
public void ArrayTraverse(int direction){
System.out.println(direction);
try{
if(direction == 0){
char original = PuzzleMatrix[position[0]][position[1]];
char newvalue = PuzzleMatrix[position[0] - 1][position[1]];
PuzzleMatrix[ position[0] - 1 ] [position[1]] = original;
PuzzleMatrix[ position[0]] [position[1]] = newvalue;
}
if(direction == 2){
char original = PuzzleMatrix[position[0]][position[1]];
char newvalue = PuzzleMatrix[position[0] + 1][position[1]];
PuzzleMatrix[ position[0] + 1 ] [position[1]] = original;
PuzzleMatrix[ position[0]] [position[1]] = newvalue;
}
if(direction == 1){
char original = PuzzleMatrix[position[0]][position[1]];
char newvalue = PuzzleMatrix[position[0]][position[1] + 1];
PuzzleMatrix[ position[0]] [position[1] + 1 ] = original;
PuzzleMatrix[ position[0]] [position[1]] = newvalue;
}
if(direction == 3){
char original = PuzzleMatrix[position[0]][position[1]];
char newvalue = PuzzleMatrix[position[0]][position[1] - 1];
PuzzleMatrix[ position[0]] [position[1] - 1 ] = original;
PuzzleMatrix[ position[0]] [position[1]] = newvalue;
}
}catch(Exception e){
System.out.println(e);
Feasibility = false;
}
}
public void PrintMatrix(char[][] PuzzleMatrix){
for (int i = 0; i < PuzzleMatrix.length; i++) {
for (int j = 0; j < PuzzleMatrix[0].length; j++) {
System.out.print(PuzzleMatrix[i][j] + " ");
}
System.out.print("\n");
}
}