【问题标题】:ArrayIndexOutOfBound when parsing int from string array从字符串数组解析 int 时的 ArrayIndexOutOfBound
【发布时间】:2017-02-16 21:02:46
【问题描述】:

我是 StackExchange 的新手,所以我会尽我最大的努力使这个问题尽可能地变得不稳定。我正在尝试从 .csv 文件创建的字符串数组中获取所有整数。文件是这样的,

  • 类型、名称、单价、数量
  • Bitem,toothpaste,1.50,2
  • Fitem,eggs,2.50,1

等等……

在我尝试将数字添加到数组之前,一切都运行良好。输出返回 ArrayIndexOutOfBoundsException。我使这个数组的 MAX_SIZE = 100。文本文件中的整数数量不超过 8。我不明白为什么会出现这个问题。我的 for 循环是完全错误的还是有更多问题?

public static void loadNums()
{
    String inputFile=("/Users/user1/Desktop/list.csv");
    File file = new File(inputFile);
    Scanner scanFile = null;

    try{
        scanFile =new Scanner(file);
    }catch(NumberFormatException | FileNotFoundException exception){
        System.out.println("Error");
    }
    if (scanFile != null)
    {
        String[] numStrs = scanFile.nextLine().split(",");
        int[] num = new int[numStrs.length];
        for (int i =0; i <numStrs.length; i++)
        {
            if (i ==0)
            {
                System.out.println("Numbers");
            }
            else 
            {
                numStrs = scanFile.nextLine().split("\\d+.,\\d+");
                for (int j =0; j <numStrs.length; j++)
                {
                    num[i] = Integer.parseInt(numStrs[i]);
                }
                System.out.println(num[i]);
            }

       }
  }

【问题讨论】:

  • 你可能想考虑一个 CSV 阅读器包,比如我的 SimpleCSV 256stuff.com/sources/simplecsv
  • @Gray 我将来肯定会使用它。但我也想看看没有这个我能不能做到。谢谢

标签: java arrays parsing for-loop java.util.scanner


【解决方案1】:

您尝试使用第一个索引 i 解析第二个数组 numStrs

num[i] = Integer.parseInt(numStrs[i]); 

所以改为使用这个,将numStrs[i] 更改为numStrs[j]

num[i] = Integer.parseInt(numStrs[j]); 

希望对你有帮助。

【讨论】:

  • 谢谢!我用 j 更改了索引 i 并修复了越界错误。但是,我收到了 NumberFormatException。有没有可能我的 .split("\\d+.,\\d+");没有正确完成?
  • 我是这么认为的,让我检查一下,我会重播
  • @P.Jacques 是的,你的正则表达式不正确,因为你得到这个错误试试这个看看我的意思public static void main(String[] args) throws IOException, URISyntaxException { String s = "Bitem,toothpaste,1.50,2"; String[] numStrs = s.split("\\d+.,\\d+"); System.out.println(numStrs.length); for (int j = 0; j &lt; numStrs.length; j++) { System.out.println(numStrs[j]); } } 结果是Bitem,toothpaste,1.,这不是一个整数
  • 好的,知道了。我将阅读有关拆分方法格式的更多信息,并尽我所能解决此问题。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 2012-10-14
  • 2016-06-29
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2011-05-25
  • 1970-01-01
相关资源
最近更新 更多