【问题标题】:How to remove the error of index out of bounds exception [duplicate]如何消除索引越界异常的错误[重复]
【发布时间】:2019-10-18 05:53:24
【问题描述】:

您好,我在 if(numList.get(x) == " " && numList.get(x+1) == " ") 行中不断收到 java.lang.IndexOutOfBoundsException。我该如何解决这个问题?

BufferedReader br = null;
        String row;
        String[] data = null;
        List<String> numList = new ArrayList<String>();

        BufferedReader csvReader = new BufferedReader(new FileReader("input file lab5.csv"));
        while ((row = csvReader.readLine()) != null) {
            data = row.split(",");
            // do something with the data

            for(int x=0; x<data.length; x++) {
                numList.add(data[x]);
            }
            numList.add(" ");
        }

        System.out.println("Make sure excel file is on src.\nNumbers extracted from file: "+numList);
        int n=0;

        for(int x=0; x<numList.size(); x++) {
            if(numList.get(x) == " " && numList.get(x+1) == " ") {
                n = x+1;
                break;

【问题讨论】:

  • for(int x=0; x&lt;numList.size()-1; x++) {?
  • numList.get(x+1) - 这也不是你在 java 中比较字符串的方式
  • 是的:不要使用==来比较字符串

标签: java csv indexoutofboundsexception


【解决方案1】:

为最后一个索引处理添加一个检查 if 子句 (x

if (numList.get(x) == " " && x < numList.size()-1 && numList.get(x+1) == " ") {

【讨论】:

  • 除非是if (numList.get(x) == " " &amp;&amp; (x &lt; numList.size()-1 || numList.get(x+1) == " ")) {
猜你喜欢
  • 2015-06-13
  • 2017-03-23
  • 2013-03-05
  • 2015-06-28
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多