在任何人对此发表评论之前,是的,我已经搜索过此东西,但找不到所需的答案。问题出在这里:
我想从列表中输出一些随机单词。我得到的输出是[Ljava.lang.String; @ 2e5c649
代码如下:
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));
}
}
答案 0 :(得分:1)
您正在尝试打印String[]
对象。只需将其包裹在Arrays.toString
System.out.println(Arrays.toString(GenerateRandomWords(5)));
Arrays#toString
从您作为参数传递给它的数组中返回一个字符串值。
与问题无关:但是,您不应在每次要调用随机实例时创建新的Random
对象,而应使用ThreadLocalRandom
所以您的随机整数看起来像这样
int rand = ThreadLocalRandom.current().nextInt(list.length);