所以我需要找到“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++;
}
最佳答案
如果我不得不猜测,您可能会遇到 NullPointerException
,因为您只初始化了 hidingSpots
数组中的一个字符串。当您第一次创建大小为 100 的数组时,字符串数组中的所有元素均为 null,直到您使用某些内容初始化它们。因此,这一行
if(hidingSpots[nutLocation].equals("Nut"))
现在导致错误,因为 hidingSpots
中的 99 个元素当前为 null
并且您无法将字符串与 null
进行比较.
字符串是对象,因此它们在数组中的默认值(与任何其他对象一样)将为 null
。这与数组中基本类型的默认值不同。例如,大小为 100 的 int
数组默认包含 100 个零。
关于java - 检索分配到数组内随机索引的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41926654/