gpt4 book ai didi

Java从字符串数组中随机生成字符串值

转载 作者:行者123 更新时间:2023-12-02 04:10:14 26 4
gpt4 key购买 nike

我正在尝试从数组自动生成字符串值并将它们添加到另一个数组,但我有一个 nullPointer 异常。

protected static Random generator = new Random();

protected static String[] townNames = { "Paris", "Sofia", "Wiena", "Amsterdam" };
protected static String[] arr;

public static void main(String[] args) {

for (int i = 0; i < towns.size(); i++) {
arr[i] = townNames[generator.nextInt(townNames.length)];
}

for (String i : arr) {
System.out.println(i);
}

}

编辑

我已经编辑了代码,现在它可以按我的预期工作。

protected static Random generator = new Random();
protected static ArrayList<String> townNames = new ArrayList<>();

protected static ArrayList<String> generatedTowns = new ArrayList<String>();

public static void main(String[] args) {
generatedArr(generatedTowns);
}

public static void generatedArr(ArrayList<String> a) {
townNames.add("Paris");
townNames.add("Sofia");
townNames.add("Wiena");
townNames.add("Amsterdam");
townNames.add("Chikago");
townNames.add("Vienna");
townNames.add("Miami");
townNames.add("Boston");
townNames.add("New Orleans");
for (int i = 0; i < 4; i++) {
String value = townNames.get(generator.nextInt(townNames.size()));
generatedTowns.add(value);
townNames.remove(value);
}

for (String i : a) {
System.out.println(i);
}
}

最佳答案

  • 您必须先创建数组才能使用它,并添加与 townNames 大小相同的随机元素。就像这样 arr=new String[townNames.length];

您可以尝试以下代码:

protected static Random generator = new Random();  
protected static String[] townNames = { "Paris", "Sofia", "Wiena", "Amsterdam" };
protected static String[] arr;

public static void main(String[] args) {
// We create an array with same size as a townNames
arr=new String[townNames.length];

for (int i = 0; i < townNames.length; i++) {
arr[i] = townNames[generator.nextInt(townNames.length)];
}

for (String i : arr) {
System.out.println(i);
}
}

关于Java从字符串数组中随机生成字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33871406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com