0

I am not so expert in java as i am learning .I am facing that error at : charArrays = s.toCharArray(); I don't know the reasons. Though i have made array size too big but still unclear.

I have added another function which is sending to crossover

 .....
            public void chr_intval(){
            int[] array = new int[100] ;
            float[]af = new float[6]; 
            String [] gf =new String[7]; // for generating generation therefore copying 
            Random randomGenerator = new Random();
            System.out.println("Chromosome     Genes    Integer value       f(x)               f'(x)    Fitness ratio");

            for(int i=1,j=1 ; i<=6; i++,j++){
                array[i] = randomGenerator.nextInt(100); // generate random 6 integers from 1<x<100
                float[] ar2 = new float[array.length];
                ar2[i]= (float)array[i];
                System.out.println("C"+j+   "            "+Genes(array[i])+"   "+array[i]+"              "+f_x(ar2[i])+"            "+fitness_function(f_x(array[i]))+"    ");//+fit_ratio(fitness_function(f_x(array[i])))); // print c1, c2,....

                af = new float[array.length];
            //  gf= new String[array.length];
                af[i]= fitness_function(f_x(array[i]));
                gf[i]= Genes(array[i]);      // send to cross_over


    //          System.out.println(fit_ratio(af));

            }
    //      System.out.print("gf"+gf[2]);
            Cross_over(gf,af);
        }


     public void Cross_over(String[] gf, float[] af) {
    // System.out.print("gf"+gf[3]); all values are coming successfully

    char[] charArrays = new char[1000];

    Character[] characterArray = new Character[charArrays.length];

    int i = 0;

    for(int j = 0; j < af.length; j++) { // comparing fit-funct
        if(af[j] > af[0]){
            af[0]= af[j];
        }
    }
    if(af[0] >= 95) {
        System.out.println("candidate's fitness "+af[0]);
    }
    else{  // start cross-over by tokenizing  the array
        // charArrays[] = gf.toCharArray();

        for (String s : gf) {
            charArrays = s.toCharArray(); // <--- Error here
        }
    }
    for(int y = 0; y < 8; y++) {
        System.out.print( characterArray[y] );
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
user3508182
  • 457
  • 1
  • 4
  • 13

2 Answers2

3

NPE here:

charArrays = s.toCharArray();

means that s is null, so at least one element in gf is null.

You should either check s != null before this line, or make sure you never add null element to gf.

BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
0

Try this:

for (String s : gf) 
{
    if(s!=null)
    {
        charArrays = s.toCharArray();  
    }
}
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
Benjamin
  • 2,257
  • 1
  • 15
  • 24