草庐IT

java - 为什么我得到一个 "ArrayIndexOutOfBoundsException"?

coder 2024-03-15 原文

我对编程和处理类作业还很陌生。现在,我不要求任何人为我编写代码,但我遇到了运行时错误。在我们需要读取文件的作业中,使用第一行“15”来初始化数组的大小,然后用每一行的信息填充数组。

编辑:我不想发布所有代码,因为我认为它看起来太长了,但由于含糊不清而遭到否决,就在这里。

文件:

15
produce,3554,broccoli,5.99,1
produce,3554,broccoli,5.99,1
produce,3555,carrots,2.23,0.25
produce,3555,carrots,2.23,0.25
produce,3555,carrots,2.23,0.25
cleaning,2345,windex,5.99,1 unit
cleaning,2345,windex,5.99,1 unit
cleaning,2345,windex,5.99,1 unit
cleaning,2345,windex,5.99,1 unit
cleaning,2346,toilet paper,12.99,4 rolls
cleaning,2346,toilet paper,12.99,4 rolls
cleaning,2335,windex,2.25,1 mini sprayer
cleaning,1342,wipes,3.99,10 units
cleaning,1342,wipes,3.99,10 units
produce,3546,lettuce,2.99,0.5

我的错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
    at Inventory.readFile(Inventory.java:45)
    at Inventory.<init>(Inventory.java:12)
    at Supermarket.main(Supermarket.java:3)

用问题中的第 45 行分类(第 45 行有注释,向右滚动)”

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Inventory{
    Product[] list;
    String[] invData;
    private int i = 0;
    public int count;

    public Inventory (String f){
        readFile(f);
    }

    public int indexOfProduct(int code){        
        for(i=0; i<list.length; i++){ 
            if (list[i] != null)
                if (list[i].getCode() == code)
                    return i;

        }
        return -1;
    }


    public Product delete(int pos){
        Product temp = new Product();
        temp = list[pos];
        list[pos] = null;
        return temp;
    }

    public void readFile(String fileName){
        try{
            File invList = new File (fileName);
            Scanner s = new Scanner(invList);
            int itemCount = s.nextInt();
            list = new Product[itemCount];
            count = itemCount;
            while (s.hasNext()){
                String line = s.nextLine();
                invData = line.split(",");
                if (invData[0].equals("produce")){
                    list[i] = new Produce(invData[1], invData[2], invData[3], invData[4]); // This is Line 45, Where the error occurs
                } else if(invData[0].equals("cleaning")){
                    list[i] = new Cleaning(invData[1], invData[2], invData[3], invData[4]);
                }
                i++;
            }//end of while loop
        } catch (FileNotFoundException Abra) {
            String error = Abra.getMessage();
            System.out.println(error);
            } 
    } // end of method

    public Product findCode(int c){
        for(int i=0; i<list.length;i++)
            if(list[1].getCode() == c)
                return list[i];
        return null;
    }//end of method
}//end of class

为什么我会收到“ArrayIndexOutOfBoundsException”?我希望有人能指出我逻辑上的缺陷,这样我就不再重复了。

最佳答案

您的问题显然与 i 的使用有关,因为这是该行中唯一的变量索引,超出范围的索引是“15”,刚好超过您的结尾15 项数组。所以,有几个问题,都围绕着 i 的使用:

正如 nhellwig 提到的,在调用此函数之前,请确保 i 实际上已初始化为 0。

此外,您非常相信文件中项目编号与实际项目数量的一致性。如果 i >= itemCount,您应该发出警告并停止尝试将项目存储在数组中,或者使用像 ArrayList 这样可以增长以容纳新项目的容器而不是固定大小的数组。

编辑:此外,我应该指出,无论您是否阅读某个项目,您都会递增 i,这意味着即使是空行也会递增 i,从而导致列表中的空白或数组溢出。由于 itemCount 是项目的数量,您应该坚持这一点,并且只有在阅读实际项目时才增加 i

本着同样的精神,您应该在调用 split() 后验证 invData.length == 5,因为文件中放错位置的逗号等也可能导致 OOB 错误.当然,对于您的项目,假设一行中以“produce”或“cleaning”开头的元素数量可能没问题,但一般来说,谨慎对待来自用户创建文件的数据很重要。

关于java - 为什么我得到一个 "ArrayIndexOutOfBoundsException"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070661/

有关java - 为什么我得到一个 "ArrayIndexOutOfBoundsException"?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  7. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  8. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  9. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  10. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

随机推荐