尝试创建用户输入的数组列表时ArrayIndexOutOfBoundsException

时间:2013-07-07 17:52:16

标签: java arrays

我想让用户为2个数组分配字符串。然后我希望他能够在分配后输入一个数字来拉出分配给字符串的值。

import java.util.Scanner;
public class Main {

    public static void main (String[]args) {

    Scanner keyboard = new Scanner(System.in);

    String customerList[] = new String[2];

    customerList[1] = keyboard.nextLine();
    customerList[2] = keyboard.nextLine();


    System.out.println("Which array  value  would you like to see?");

    int listNum = keyboard.nextInt();

        System.out.println(customerList[listNum]);
    }

}

1 个答案:

答案 0 :(得分:4)

数组的第一个值的索引为0而不是1:

customerList[0] = keyboard.nextLine();
customerList[1] = keyboard.nextLine();

这是一个很棒的Java Arrays教程:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html