-4

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)

1 Answers1

0

I'm not fully sure your code should do, but at least, the problem is in line {return charArray[i]

You get an error because at this moment i is 4, so it's out of the array scope.

This way it will at least work, but I'm not sure if it gives you expected result:

public class App{

public static void main(String[]args){

    App theApp = new App();
}

    public App(){


        char[] currentCharacters = randomizeCodeBlock();

         for(int i=0; i<4; i++){
         System.out.println(currentCharacters[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;
    }
}

What I changed: function randomizeCodeBlock() returns a randomized array. Then the content of the array is printed to the standard output as you proposed.

Just in case you can use Java collections, please take a look at this article, to make sure that the Collection.shuffle method is not good for you.

Vicctor
  • 803
  • 6
  • 13