0

I'm making a java program for schoolwork where you can add, move and remove stuff from containers. I have to use commands like "add 100" "remove 50". The stop command "lopeta" is only one word, but other commands have two parts, command and int. When I use the stop command, I get Index out of bounds error, but everything else works. I guess it's because the stop command only has the word and no int, but how do I prevent this error from happening? It works if I use "lopeta 0", but I want to only use "lopeta". Sorry the names are in finnish but I hope you can make sense of this. Here's my code

        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;
            }
        }

1 Answers1

0
 String[] osat = luettu.split(" ");
 String komento = osat[0];
 int maara = Integer.valueOf(osat[1]);

You're splitting the string based on space (" "). Now when there is the string "lopeta 0" you get the array ["lopeta","0"]. When you do osat[1] you get "0", but when you only have string "lopeta" and you split the string the resulting array has only 1 element ["lopeta"]. So you'll get ArrayIndexoutOfBoundsException because there is no 2nd element.

Either you can check the size of the array before accessing the element or if you have an idea about exceptions you can use a try, catch block to handle.

nps
  • 46
  • 4