0

我的 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)];,“说表达式的类型必须是数组类型,但它解析为字符串”。然后,当我将类型更改为 Array 时,它会沿着核心类抛出各种错误。我不知道我做错了什么。任何人都可以帮忙吗?

4

2 回答 2

2

如果你必须使用静态变量,这里是如何做到的。

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);
    }
}
于 2013-05-10T09:12:36.140 回答
0

您将核心用作数组,但它被定义为字符串

private static String core;

所以你不能做

tpiCore.core[...]

你应该做类似的事情

tpiCore.insults[...]
于 2013-05-10T09:01:16.077 回答