我已经得到了这个异常,我不知道如何去修复它:
java.lang.ArrayIndexOutOfBoundsException: 3在while循环中。下面是我的代码:
public class NameSearch {
static String[] names = new String[3];
void populateStringArray() {
names[0] = "Ben";
names[1] = "Thor";
names[2] = "Zoe";
names[3] = "Kate";
}
public static void main(String[] args) {
String pName;
int max = 4;
int current = 1;
boolean found = false;
Scanner scan = new Scanner(System.in);
System.out.println("What player are you looking for?");
pName = scan.next();
while (found == false && current <= max) {
if (names[current] == pName) {
found = true;
} else {
current = current + 1;
}
}
if (found == true) {
System.out.println("Yes, they have a top score");
} else {
System.out.println("No, they do not have a top score");
}
}
}该代码旨在要求用户输入一个名称,然后它将检查该名称是否在数组中(简而言之)。
我的集成开发环境(Eclipse)显示错误存在于if (names[current] == pName){行中。
发布于 2015-09-10 00:19:56
这是因为你有条件current <= max。如果max为4,则意味着current可以等于4,并且数组中没有索引4。这就是为什么错误来自names[current],你试图访问索引4但它并不存在。您应该只使用<而不是<=,或者使用max = 3而不是4。
附注:
0开始如果current等于1当循环开始时,它永远不会查看数组中的第一个索引。true或在false之前添加!,而不是执行== true或== false。因此,在这种情况下,您可以使用while(!found.int而不是while(found == false,通常做法是递增1时使用current++,递增1以上时使用+= (例如,current +=2会将current递增2)。发布于 2015-09-10 00:20:37
问题出在这个条件下:found == false && current<= max - Sidenote:found == false可以简化为!false,但仍然会得到相同的结果。current<=max允许使用current == max运行循环,而max被定义为4。因此,您将在names[4]处获得一个越界的读取。最简单的解决方案是将条件从current <= max更改为current<max。由于数组在java中是从0开始的,这将导致程序省略名字,即names[0]。
另一个附带说明:使用常量作为max是一种非常容易出错的方法。改为使用names.length初始化max。
发布于 2015-09-10 00:21:18
这里:
static String[] names = new String[3];您正在初始化一个容量为3项的数组,而不是最大索引为3的数组。要获得一个包含0、1、2和3的数组,这是4项,因此您需要像这样初始化数组:
static String[] names = new String[4]; // (0-3)此外,循环和数组都是从零开始的,所以您需要从current 0开始,而不是从1开始循环您的数组。
此外,也是最后一点,您需要在while循环中将<=切换为<,因为我们希望它只上升到3。
https://stackoverflow.com/questions/32484615
复制相似问题