-2

Before anyone comments about it, yes I already searched for this thing but I couldn't find the answer I needed. Here's the problem:

I want to output a few random words from a list. The output I get is [Ljava.lang.String;@2e5c649

Here's the code:

import java.util.Random;
public static String[] GenerateRandomWords(int n)
{
    String[] list = {"random" , "school", "game", "habit", "window", "animal", "hidden", "puzzle", "coding", "gaming", "programmer", "box", "laptop", "swing", "jungle",
            "house", "picture", "program", "table", "cookie", "project", "mathematics", "think", "graphics", "interface", "innovation", "analysis", "reduce", "screen",
            "company", "cow", "banana", "apple", "milk", "tea", "coffee", "job", "cake", "collection", "movie", "toolkit", "tree", "speaker", "microphone", "workshop",
            "progress", "story", "article", "music", "script", "language", "instruction,", "key", "sun", "age", "joy", "volume", "orange", "hotdog", "museum", "career",
            "radical", "outside", "brother", "balance", "reserve", "action", "notebook", "research", "complete", "remember", "teenager"};
    String newarr[] = new String[n];


for (int i=0;i<n;i++)
    {
        int rand = new Random().nextInt(list.length);
        newarr[i]=list[rand];

    }

    return newarr;

}

public static void main(String[] args) {
    System.out.println(GenerateRandomWords(5));
}

}

CasualNoob
  • 41
  • 2

1 Answers1

1

You are trying to print a String[] Object. Just wrap it around Arrays.toString

System.out.println(Arrays.toString(GenerateRandomWords(5)));

Arrays#toString returns a String value from the Array you pass to it as a param.

Not related to the question: But You shouldn't create a new Random object everytime you want to call a Random instance instead use ThreadLocalRandom

So your random int will look like this

int rand = ThreadLocalRandom.current().nextInt(list.length);
SamHoque
  • 2,978
  • 2
  • 13
  • 43