error in comparison using substring

Asked

Viewed 65 times

2

maquina += numeroale.nextInt(4);
        maquina += numeroale.nextInt(4);

        //vez da mqauina
    for (int i = 0; i < maquina.length(); i++) {

        System.out.println("valor atual"+maquina.substring(i,1));

        if((maquina.substring(i,1)).equals("0")){
            System.out.println("0 pressed");
            b1.setBackground(Color.white);




            play("b1");




        }
        else if((maquina.substring(i,1)).equals("1")){
            System.out.println("1 pressed");
            b2.setBackground(Color.white);

            play("b2");

        }
        else if((maquina.substring(i,1)).equals("2")){
            System.out.println("2 pressed");
            b3.setBackground(Color.white);


            play("b3");



        } else if((maquina.substring(i,1)).equals("3")){
            System.out.println("3 pressed");
            b4.setBackground(Color.white);


        play("b4");

        }
        else{

        }



    }   

the code cannot compare the second position, but the first goes after the error

  • Where does this variable come from maquina and what does it hold? Add a [mcve]. As I told you in the other question, adding a loose, non-replicable piece only makes it harder for you to get an answer.

  • just wanted to know if the comparison is correct in if

  • the number variable generates random numbers

  • If machine is integer, why are you using substring??

  • machine is a string

1 answer

1

The problem is that the second parameter (endIndex) de substring is exclusive.

It also indicates the position where it should end, not the number of characters as it is done in other languages.

This means that the endIndex must be larger (at least 1) than the beginIndex. Hence your code fails in the second iteration where the value of i is equal to 1.

Correct for the next, everywhere:

maquina.substring(i, i + 1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.