【问题标题】:Java .split() Array out of boundsJava .split() 数组越界
【发布时间】:2019-05-10 00:14:45
【问题描述】:

对于以下代码,我不断收到此数组越界错误。

brock.txt = 反射程序,例程,箭,蛇游戏,

public static void main(String[] args) {
    String filename = "brock.txt";
    String line; 
    String [] cities = {};
    int x = 0;
    try {

    BufferedReader eshread = new BufferedReader( new FileReader (filename));
        line = "";

        while ((line = eshread.readLine()) != null ) {
        String[] store = line.split(",");
        System.out.println(store[0]);
        System.out.println(store[1]);
        System.out.println(store[2]);
        cities[x] = store[2];            //< keep getting an error here
        x++;
        }//end while loop
        eshread.close();
        }//end try
    catch(IOException iox) {
    System.out.println("failiure");
    }//end catch

【问题讨论】:

  • String [] cities = {} 这就是原因

标签: java arrays eclipse split


【解决方案1】:

与其他 cmets 一致。问题在于 cities 数组的大小被设置为 0,因此数组越界的问题。 我尝试了以下代码,如果您想使用 String 数组,它可以工作。 否则,如果未定义大小,ArrayList 是更好的解决方案。

    String [] cities = new String[10];

【讨论】:

    【解决方案2】:

    您使用空数组 ({}) 初始化了 cities,这意味着它的长度为 0(不是 null,而是一个空数组)。通过使用cities[0],您期望它至少有一个元素,这是不正确的。

    要解决此问题,请使用 ArrayList&lt;String&gt; 而不是字符串数组。

    【讨论】:

      【解决方案3】:

      您必须定义城市的大小或使用列表。

      【讨论】:

        【解决方案4】:

        String [] cities = {}会使数组大小为0,当x大于0时会报错,就是这个原因,所以需要先把cities设置成固定大小或者使用@987654325 @去做吧

        【讨论】:

          猜你喜欢
          • 2015-12-29
          • 2013-04-02
          • 2013-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多