0

我正在为作业制作一个 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;
            }
        }
4

1 回答 1

0
 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 块来处理。

于 2021-12-08T18:05:59.253 回答