【问题标题】:Index out of bounds despite not being out of bounds?尽管没有超出范围,但索引超出范围?
【发布时间】:2022-01-13 15:10:09
【问题描述】:

我正在为作业制作一个 Java 程序,您可以在其中添加、移动和删除容器中的内容。我必须使用“添加 100”“删除 50”之类的命令。停止命令“lopeta”只有一个词,但其他命令有两个部分,command 和 int。当我使用 stop 命令时,我得到 Index out of bounds 错误,但其他一切正常。我猜是因为 stop 命令只有 word 没有 int,但是如何防止这个错误发生呢?如果我使用“lopeta 0”,它会起作用,但我只想使用“lopeta”。对不起,名字是芬兰语,但我希望你能理解这一点。 这是我的代码

        String luettu = lukija.nextLine();
        String[] osat = luettu.split(" ");
        String komento = osat[0];
        int maara = Integer.valueOf(osat[1]);
        if(luettu.equals("lopeta")) {
                break;
            } 
        if(komento.equals("lisaa")) {
            if(maara < 0) {
                ensimmainen = ensimmainen + 0;
            } else {
                ensimmainen = ensimmainen + maara;
            }
            if(ensimmainen > 100) {
                ensimmainen = 100;
            }
        } else if (komento.equals("siirra")) {
            if(maara < 0) {
                ensimmainen = ensimmainen + 0;
            } if(maara > ensimmainen) {
                ensimmainen = 0;
            } if (toinen + maara > 100) {
                toinen = 100;
            } else {
                ensimmainen = ensimmainen - maara;
                toinen = toinen + maara;
            }
        } else if (komento.equals("poista")) {
            if(maara > toinen) {
                toinen = 0;
            } else {
                toinen = toinen - maara;
            }
        }

【问题讨论】:

  • osat的字符串拆分和访问前移动检查if(luettu.equals("lopeta"))
  • 你应该用行号添加实际错误。
  • 电脑没有错。如果您的代码引发 IndexOutOfBoundsException,则索引 超出范围。不相信是没有用的。

标签: java arrayindexoutofboundsexception


【解决方案1】:
 String[] osat = luettu.split(" ");
 String komento = osat[0];
 int maara = Integer.valueOf(osat[1]);

您正在根据空格 (" ") 拆分字符串。现在,当存在字符串“lopeta 0”时,您将获得数组 ["lopeta","0"]。当您执行 osat[1] 时,您会得到“0”,但是当您只有字符串“lopeta”并且拆分字符串时,结果数组只有 1 个元素 [“lopeta”]。所以你会得到 ArrayIndexoutOfBoundsException 因为没有第二个元素。

您可以在访问元素之前检查数组的大小,或者如果您对异常有所了解,可以使用 try, catch 块来处理。

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 1970-01-01
    • 2020-08-18
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2018-03-01
    相关资源
    最近更新 更多