java - 从字符串数组中解析 int 时出现 ArrayIndexOutOfBound

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

我是 StackExchange 的新手,因此我会尽力使这个问题尽可能不稳定。我试图从 .csv 文件创建的字符串数组中获取所有整数。该文件看起来像这样,

  • 类型、名称、单价、数量
  • Bitem,牙膏,1.50,2
  • Fitem,鸡蛋,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]);
            }

       }
  }

最佳答案

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

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

因此,不要使用此方法,而是将 numStrs[i] 更改为 numStrs[j]:

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

希望这可以帮助你。

关于java - 从字符串数组中解析 int 时出现 ArrayIndexOutOfBound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42284547/

相关文章:

java - Guice 子模块阻止继承绑定(bind)

c++ - 访问 std::pair 数组的元素时出错

Java转换字符串,具有毫秒至今的对象

javascript - 数组属性未解析为 angularjs 指令

javascript - Express Subscribe 调用中的 JSON 数组出现 Angular HTML 绑定(bind)错误

java - 尝试解析具有重复属性名称的 xml

java - 解析 JSON 文件

Java:如何正确解析字符串到日期?

java - 如何验证Spring MVC Web应用程序中是否已设置连接池?

java - Android 不支持的 key 大小 : 3 bytes on decrypt text