如何使String数组与另一个String数组相等

时间:2016-01-04 02:35:14

标签: java arrays

String[] mySecret;
String[] colours = {"R","Y","Bl","G","O","Pu","Pi","Br"};

public void getuserInput() {
    numColours = min + (int)(Math.random() * ((max-min) +1));
    numPegs = min + (int)(Math.random() * ((max-min) +1));
}
public void setSecret() {
    for (i=0; i<numColours; i++) {
        mySecret[i] = colours[new Random().nextInt(colours.length)];
    }
}

这是我的代码的一小部分。当我运行它时,我得到一个NullPointerException。有没有其他方法来获取mySecret,它是一个字符串数组,包含指定数量的颜色,但从颜色字符串数组中随机选择。任何帮助将不胜感激,谢谢。

2 个答案:

答案 0 :(得分:0)

您需要更多地阅读Java语言。

public void setSecret() {
    mySecret = new String[numColours];
    for ( int i=0; i<numColours; i++) {
        mySecret[i] = colours[new Random().nextInt(colours.length)];
    }
}

答案 1 :(得分:0)

你应该像这样初始化你的数组mySecret

 String[] colours = {"R","Y","Bl","G","O","Pu","Pi","Br"};
 String[] mySecret = new String[colours.length];