gpt4 book ai didi

Java-数组/字符串混搭错误?

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

目前我的 Java 代码有一个小问题,我无法从数组中选取随机字符串。我的代码片段在这里:

 private static String core;
{

String[] insults = new String[15];
insults[0] = "So's your mum.";
insults[1] = "I hate you too.";
insults[2] = "Freak!";
insults[3] = "Your balls are like peas.";
insults[4] = "You're so ugly, your birth certificate was an apology letter from the condom factory.";
insults[5] = "Ooh, take me to the burn unit.";
insults[6] = "That insult was like your dick- Pathetic.";
insults[7] = "Your mum looks like a dog. I was brought up not to lie.";
insults[8] = "Can you look away? It's killing my face...";
insults[9] = "If you had a house for every good insult you gave me, you'd still be living on the streets!";
insults[10] = "Shut up, you'll never be the man your mother is.";
insults[11] = "Shut up, you'll never be the man your mother is.";
insults[12] = "Oh my God... Was your face squashed in a vice at birth?";
insults[13] = "I know you are, but what am I?";
insults[14] = "Oh, okay then...";
double count = 0;
};


public static void output(String output) {
String insult1 = tpiCore.core[(new Random()).nextInt(insults.length)];
}

从这里你可能可以看到我正在尝试做什么。从上面的列表中随机选择一个侮辱。如果我尝试运行代码,它会在 tpiCore.core[(new Random()).nextInt(insults.length)]; 处抛出错误,“表示表达式的类型必须是数组类型,但它解析为 String”。然后,当我将类型更改为 Array 时,它会在核心类中抛出各种错误。我不知道我做错了什么。有人可以帮忙吗?

最佳答案

如果必须使用静态变量,请按以下步骤操作。

public class TpiCore {

private static String[] insults = new String[15];
static {
insults[0] = "xxx";
insults[1] = "yyy";
insults[2] = "zzz";
// etc...
}

public static void main(String[] args) {
String insult1 = TpiCore.insults[new Random().nextInt(insults.length)];
System.out.println(insult1);
}
}

但是我会建议更像这样的东西。祝你好运。

public class TpiCore {

private String[] insults = new String[15];

public TpiCore() {
insults[0] = "xxx";
insults[1] = "yyy";
insults[2] = "zzz";
// etc...
}

private String randomInsult() {
return insults[new Random().nextInt(insults.length)];
}

public static void main(String[] args) {
TpiCore core = new TpiCore();
String insult1 = core.randomInsult();
System.out.println(insult1);
}
}

关于Java-数组/字符串混搭错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16478474/

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