samedi 5 mai 2018

Returning characters to an array from a method in JAVA

I am trying to return 4 characters to an array from a method but get the error shown below. I have tried to call the method in two positions so far and have commented them out below. What is the correct way to do this?

class App{

public static void main(String[]args){

    App theApp = new App();
}

    // position 1 - RandomizeCodeBlock(); 

    char[] charactersAllowed;
    char[] charArray;

    public App(){

        // position 2 - RandomizeCodeBlock(); 

         for(int i=0; i<4; i++){
         System.out.println(charArray[i]);
         }
    }

    public char RandomizeCodeBlock()
    {      
          char[] charactersAllowed = {'A','B','C','D','E','F','G'};
          charArray = new char[4];
          int i;

          for(i = 0; i < charArray.length; i++) {
          charArray[i] = charactersAllowed[(int) (Math.random() * 4)];
          }return charArray[i];
    }
}

I get this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at App.RandomizeCodeBlock(App.java:33)
    at App.<init>(App.java:17)
    at App.main(App.java:5)




Aucun commentaire:

Enregistrer un commentaire