字符串数组; java.lang.ArrayIndexOutOfBoundsException:10

时间:2014-11-28 18:49:06

标签: java arrays constructor indexoutofboundsexception

我有两个类基本上作为最简单的数据库,用户应该输入一个字符串,程序使用包含所有方法的类将其添加到数组中。除了当我输入第一个名字时,它给了我java.lang.ArrayIndexOutOfBoundsException:0。我知道这意味着没有为数组分配内存,但我想我在我的第二个类中做了这个,其中有一个构造函数定义了数组的大小。我没有经验足以使用数组来自行修复此调试。很多帮助都会被哄骗!

import java.util.*;

    public class TestDatabase {
    //contant value for data base 'size' of array
    public static final int constant = 10;
    public static void main (String[] args){
    //Database object sets the array size to constant value
    Database get = new Database(constant);
    //input stream
    Scanner in = new Scanner (System.in);

    //varaibles for the count and index; prompt
    int count = 0;
    int index = 0;
    System.out.println("Please enter 10 names to add them to the database. Name: " + (count +=               1));
    //while the count is lower than or equal to 10...                                                                                 
    while(count<=10){
        //input stream equal to input
        String input = in.nextLine();
        //if the count equals, stop the loop
        if (count == 10)
        {
            //breaks the loop
            break;
        }
        //prints out the current name
        System.out.print(" Name: " + (count +=1));
        //adds the input to the array
        get.add(index,input);
        //increments index by 1
        index++;
    }
    //prints the array
    get.print(); 
}

}

这是我的所有方法的课程:

import java.util.*;

public class Database{
//size of array
public int _size;
//array which has a varaible size
String[] userArray = new String[_size];
//contructer for the array size
public Database(int size){
    _size = size;
}
//add method which adds a value to an index of an array
public void add(int index, String name){
   //the values of string is placed into some index of the array
   userArray[index] = name;
}
//print method which prints the contents of the array
public void print(){
    //prints array
    System.out.println(Arrays.toString(userArray));
}
//sort method which sorts the array
public void sort(){
    //sorts the array
    Arrays.sort(userArray);
}
//find method which finds a particular string in any index
public void find(String value){
    Arrays.asList(userArray).contains(value);
}

}

3 个答案:

答案 0 :(得分:0)

在构造函数设置_size之前,

userArray init的长度为零。在构造函数中创建userArray。

创建类时会执行后续步骤:

  1. _size init with 0
  2. userArray init,零长度数组
  3. _size init,大小值。

答案 1 :(得分:0)

你的ArrayList永远不会被正确实例化,你需要将它移动到构造函数中,所以当调用new运算符时,会使用传递的size变量创建arraylist,如下所示:

public Database {
    private String[] data;

    public Database(int size){
        this.data = new String[size];
    }
}

使用当前代码,在实际给出大小之前创建数组,因此默认大小为0.

答案 2 :(得分:0)

更改以下代码

   String[] userArray;
    public Database(int size){
        _size = size;
        userArray = new String[_size];
    }