jeudi 22 février 2018

How do i return random String from array list?

Im trying to return a string from my arraylist but i keep getting an outofbounds exception which i assume its a problem with the "RandomArray.size-1". The array has 10 strings and I need 1 random one to be generated.

///////////////my arraylist where the string is stored///////////////

 ArrayList<String> RandomArray = new ArrayList<>();

/////////my else statment to get the random string//////////

 else {
         phrase=RandomArray.get(rng.nextInt(RandomArray.size()-1));  
    }
  /////////////////////`where i added the phrases into the list`
public String randomPhrases() {

    String phrase1 = "its morping time";
    RandomArray.add(phrase1);
    String phrase2 = "its lit";
    RandomArray.add(phrase2);
    String phrase3 = "head over heels";
    RandomArray.add(phrase3);
    String phrase4 = "shot in the dark";
    RandomArray.add(phrase4);
    String phrase5 = "a chip on your shoulder";
    RandomArray.add(phrase5);
  return string;




Aucun commentaire:

Enregistrer un commentaire