【问题标题】:avoiding array index outof bound exception while splitting string拆分字符串时避免数组索引越界异常
【发布时间】:2015-01-31 14:03:51
【问题描述】:

我正在尝试读取文件并逐行拆分字符串行。这是文件中的示例字符串

Decorative Platters--------Home & Kitchen->Home & Décor->Home Décor Accents
Hookah--------Watches & Jewellery->Fashion Jewellery->Bangles
hookah--------

在这种情况下,第三行在点之后没有任何内容。

private static void getCategoriesFromFileAndMAtch()  {
    try {
        BufferedReader br=new BufferedReader(new FileReader("mapping_log"));
        String eachLine;
        while((eachLine = br.readLine()) != null)
        {
            String input1, input2, tempString;
            input1=eachLine.split("--------")[0];
            tempString=eachLine.split("--------")[1];
            if(!(eachLine.split("--------")[1].isEmpty()))
            {
                tempString=eachLine.split("--------")[1].split("::=>")[0];
                System.out.println(input1+"   "+tempString);
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();        
    }

}

因为 [1] 的值是空的,我得到了异常并且程序停止了。我怎样才能避免这种情况?我在 if 循环中检查它是否为空。这还不够吗?

【问题讨论】:

    标签: java string split substring


    【解决方案1】:

    当您编写以下行时,您假设该元素存在,但在您的情况下它根本不存在,并且if 语句本身会因异常而爆炸。

    if(!(eachLine.split("--------")[1].isEmpty()))
    

    改为检查split()的返回值的长度。

    if(eachLine.split("--------").length > 1)
    

    【讨论】:

    • 我想你想要if(eachLine.split("--------").length > 1) ——length 是数组的属性,而不是方法。 (修复太小,无法提交修改。)
    • @Ben,谢谢!我修好了。
    【解决方案2】:

    建议:

    1. 不要做 tempString = eachLine.split("--------");多次,每次执行此操作时,它都会一遍又一遍地拆分线路(昂贵的操作)。因此,始终拆分一次并尝试重复使用以下示例中提到的结果。
    2. 在不知道数组长度的情况下,使用array.length找出并添加相应的条件。

    示例:

    String input1, input2, tempString;
    String [] parts = eachLine.split("--------");
    input1 = parts[0];
    
    if (parts.length > 1) {
        input2 = parts[0];
        tempString=input2.split("::=>")[0];
        System.out.println(input1 + "   " + tempString);
    }
    

    【讨论】:

      【解决方案3】:

      对于第三种情况,eachLine.split("--------") 将返回一个长度为 1 的数组,因此当您访问索引为 1 的数组时,即 eachLine.split("--------")[1] 它给出了一个例外。可以先检查split函数返回的数组是否大于1

      if(eachLine.split("--------").length > 1 && !(eachLine.split("--------")[1].isEmpty()))
      {
       tempString=eachLine.split("--------")[1].split("::=>")[0];
       System.out.println(input1+"   "+tempString);
      }
      

      【讨论】:

        猜你喜欢
        • 2015-07-13
        • 2012-01-31
        • 2013-10-05
        • 2019-08-01
        • 2013-12-08
        • 2014-10-16
        • 2017-03-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多