如何解决“java.lang.IndexOutOfBoundsException”错误?

时间:2015-08-06 02:54:47

标签: java

这是我的代码。它是一个随机字符串生成器。当我运行它时,如果加在一起的字母和字符数小于所需的数字位数,我会得到一个错误代码,如下所示。有人可以帮我解决这个问题吗?

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class list {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Random num = new Random();
        System.out.println("How many characters do you want?");
        Scanner Digits = new Scanner(System.in);
        int digits = Integer.parseInt(Digits.nextLine());
        System.out.println("How many different numbers do you want? 1-10 please");
        int number = Integer.parseInt(Digits.nextLine());
        System.out.println("Which letters do you want? One at a time, press enter after each letter. If done, just press enter.");
        List<String> characters = new ArrayList<String>();
        while (true) {
            System.out.println("Add your characters.");
            String character = Digits.nextLine();
            if (character.equals("")) {
                break;
            } else {
                characters.add(character);
            }
        }

        List<Object> andrew = new ArrayList<Object>();
        for (int x = 0; x < digits; x++) {
            andrew.add(num.nextInt(number));
            andrew.add(characters.get(x));
        }

        for (int x = 0; x < andrew.size(); x += 2) {
            System.out.print(andrew.get(x));
        }
    }
}

例外:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at list.main(list.java:33)

1 个答案:

答案 0 :(得分:0)

当您尝试从超出其大小的数组中选择值时,会出现IndexOutOfBoundsException。在这个例子中,你试图获得[3]的值。您可以从堆栈跟踪中读取这么多内容:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3

java中的数组从索引[0]开始,而不是索引[1],因此长度为3的数组只有索引[0][1]和{{1} }。

当数组仅扩展到[2]时,尝试在[3]获取值将导致此错误。

但是,另一个答案实际上是问题所在。堆栈跟踪表明它位于第33行,即:

[2]