检索已分配到数组内的随机索引的字符串

时间:2017-01-29 22:26:11

标签: java arrays random

所以我需要找到存储“Nut”字符串的位置。我认为我的代码工作得很好,但很明显,ide只是让我犯错误。

Random rd = new Random();
String[] hidingSpots = new String[100];
hidingSpots[rd.nextInt(hidingSpots.length)] = "Nut";
System.out.println("The nut has been hidden ...");
int nutLocation = 0;
while (nutLocation < hidingSpots.length) {
    if (hidingSpots[nutLocation].equals("Nut")) {
        System.out.println("Found it! It's in spot# " + hidingSpots[nutLocation]);
    }
    nutLocation++;
}

1 个答案:

答案 0 :(得分:2)

如果我不得不猜测,你可能会得到NullPointerException,因为你只在hidingSpots数组中初始化了一个字符串。当您第一次创建大小为100的数组时,字符串数组中的所有元素都为null,直到您使用某些内容初始化它们。因此,这一行

if(hidingSpots[nutLocation].equals("Nut"))

现在导致错误,因为hidingSpots中的99个元素当前为null,您无法将字符串与null进行比较。

字符串是对象,因此它们在数组中的默认值与任何其他对象一样,将是null。这与数组中基元类型的默认值不同。例如,大小为100的int数组默认包含100个零。