如何在Java中用“KGBV”生成随机字符串

时间:2018-03-19 15:25:42

标签: java

我正在尝试创建一个像摇滚,纸张,剪刀这样的游戏,除了四个不同的动作而不是三个。这些动作都由K,G,B,V表示。对于计算机的移动,我需要生成一个随机的字母来对抗人类。我还需要它是一个字符串,以便我可以将它与人类回答的字符串进行比较。这是我所拥有的,但它只适用于字符:​​

 public static String computerMove() {
    String move = "";
    Random rand = new Random();
    String abc = "KGBV";

char letter = abc.charAt(rand.nextInt(abc.length()));


    if (letter == 'K') {
        move = K;
    } else if (letter == 'B') {
        move = B;
    } else if (letter == 'G') {
        move = G;
    } else if (letter == 'V') {
        move = V;
    }
    return move;



}

4 个答案:

答案 0 :(得分:1)

尝试使用字符串初始化数组并在该数组中使用随机索引。

这样的事情:

String[] moves = {"one", "two", "three", "four"};
int index = rand.nextInt(moves.length);
String move = moves[index];

答案 1 :(得分:1)

你可以这样做:

Random rand = new Random();
String[] moves = {"G","K","N","V"};
return moves[rand.nextInt(moves.length)];

答案 2 :(得分:0)

如果您想从字符串中获取随机单字符串:

int r = rand.nextInt(string.length());
return string.substring(r, r + 1);

答案 3 :(得分:0)

试试这个

public static string computerMove() {
    String move;
    Random rand = new Random();
    int randNum = rand.nextInt();

    if (randNum == 0)
        move = "k";
    else if (randNum == 1)
        move = "B";
    else if (randNum == 2)
        move = "G";
    else
        move = "V";

    return move;
}