计算按键时ArrayIndexOutOfBoundsException

时间:2014-12-17 19:28:58

标签: java arrays

我有一个程序可以自动计算按下手机键盘上的数字的次数,但我收到一个奇怪的错误,我不知道为什么。

错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at naloga11.main(naloga11.java:23)

代码:

//naredi tipkovnico

    int max_num = 9;
    String niz = "ta veseli dan ali maticek se zeni xyzq";
    String [] tipkovnica = new String[max_num]; 
    int [] stejvnose = new int[max_num];
    tipkovnica[1] = " ";
    tipkovnica[2] = "abc";
    tipkovnica[3] = "def";
    tipkovnica[4] = "ghi";
    tipkovnica[5] = "jkl";
    tipkovnica[6] = "mno";
    tipkovnica[7] = "pqrs";
    tipkovnica[8] = "tuv";
    tipkovnica[9] = "wxyz";

3 个答案:

答案 0 :(得分:2)

数组从0开始计数,因此在这种情况下从0到8。

答案 1 :(得分:1)

数组的索引从0开始,max_num的值为9,但tipkovnica[9]确实是索引10,这就是你获得ArrayIndexOutOfBoundsException的原因。将您的指数更改为以下内容:

tipkovnica[0] = " ";
tipkovnica[1] = "abc";
tipkovnica[2] = "def";
tipkovnica[3] = "ghi";
tipkovnica[4] = "jkl";
tipkovnica[5] = "mno";
tipkovnica[6] = "pqrs";
tipkovnica[7] = "tuv";
tipkovnica[8] = "wxyz";//9th index, same as your max_num value

答案 2 :(得分:0)

Java使用从零开始的数组。因此,如果大小为5,则元素从索引[0-4]运行。 这意味着您将按如下方式迭代它们:

for (int i=0; i<array.length; i++) System.out.println(i);

哪些(对于新人来说)确实等同于

int i = 0
while (i < array.length)
{
  System.out.println(i)
  i = i + 1;
}

但是,请遵循一些可以帮助您使代码更漂亮的想法。

// this is a more pretty way to initialize an array.
// the cute thing, is that you do not even need to specify the capacity.
// however, the array is still fixed size of course.
String[] elements = { "element1", "element2", "element3" };

// this will not compile (and may be confusing)
String[] elements;
elements = { "element1", "element2", "element3" };

// if you do it in 2 lines, then you need to add the class of the array.
String[] elements;
elements = new String[] { "element1", "element2", "element3" };

// but really in 95% of times it is better to use an ArrayList.
List list = new ArrayList();
list.add("element1");
list.add("element2");
list.add("element3");

// however, even better is to add generics.
List<String> list = new ArrayList<String>();

// if you use Java 7 language level settings or higher
// which probably is the case.
List<String> list = new ArrayList<>();

关键是,几乎不需要对数组或集合的大小进行硬编码。