java.lang.ArrayIndexOutOfBoundsException:3 while循环 [英] java.lang.ArrayIndexOutOfBoundsException: 3 in a while loop

查看:210
本文介绍了java.lang.ArrayIndexOutOfBoundsException:3 while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经得到这个例外,我不知道如何去修复它:

I've been getting this exception and I've no idea how to go about fixing it:

java.lang.ArrayIndexOutOfBoundsException: 3

,而循环。这里是我的code:

in the while loop. Here's my code:

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");
        }
    }
}

在code意在要求用户输入一个名称,它会检查,看看是否名字是阵列中(简言之)。

The code is meant to ask the user to input a name and it will check to see if the name is in the array (in a nutshell).

我的IDE(Eclipse中)说,错误在于行如果(名称[现行] == PNAME){

My IDE (Eclipse) says that the error lies in the line if (names[current] == pName){.

推荐答案

您的索引在循环的数组元素 1 4 (含)的,当你需要将它们编索引 0 和 3 (含)

You are indexing your array elements in the loop between 1 and 4 (inclusive), when you need to be indexing them between 0 and 3 (inclusive).

修改电流 0 启动和最大 3 ,你应该都不错。

Change current to start at 0, and max to be 3 and you should be all good.

有关或许是更好的选择,考虑把你的邮件列表的名字在 HashSet的键,不需要在所有迭代。例如。

For perhaps an even better alternative, consider putting your list of names in a HashSet and not needing to iterate at all. E.g.

Set<String> names = new HashSet<String>();
names.add("Ben");
names.add("Thor");
names.add("Zoe");
names.add("Kate");

if (names.contains(pName)) {
//...

如果姓名的顺序是非常重要的,那么你可以使用列表来代替,其中也有一个包含方法(只是不一般同样有效,在地图实施.. O(N) VS O(1)典型值)。如果名称列表中的数量比较少或性能不是一个问题,那也没什么关系无论哪种方式。

If the ordering of the names is important, then you could use a List instead, which also has a contains method (just not generally as efficient as that in a Map implementation.. O(n) vs O(1) typically). If the number of names in your list is small, or performance is not an issue, then it will not matter either way.

这篇关于java.lang.ArrayIndexOutOfBoundsException:3 while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆