How to make a counter that increases if a letter is not found in a word: AVA

1

Good afternoon! My problem is this, try to make a for loop so that I traversed letter by letter a word, and when I did not find it, the counter increased by one and my problem was that when I went through the whole word I increased by one every time the word does not appear ...

Here I leave the piece of code in case I did not understand well ...

primerJugador = jugador1.getText();
       comparacion1 = primerJugador.charAt(0);

       for (int i=0;i<palabra.length();i++) {
        comparacion2 = palabra.charAt(i);
           if (comparacion1==comparacion2) {
               JOptionPane.showMessageDialog(null, "Letra "+comparacion1 + " encontrada");
               encontrado = true;
           }
           else{
               encontrado = false;
           }
        }

       if(encontrado)
       {
            contador = contador+1;
       }      

The program runs through all the letters and adds the contador the times you can not find it.

    
asked by user54538 01.08.2017 в 00:29
source

1 answer

0

Simply add the variable for the counter in the else , which is where it would enter if you can not find the word:

        for (int i=0;i<palabra.length();i++) {
           comparacion2 = palabra.charAt(i);
           if (comparacion1==comparacion2) {
               JOptionPane.showMessageDialog(null, "Letra "+comparacion1 + " encontrada");
               encontrado = true;               
           }else{
               contador++;
               encontrado = false;
           }
        }

 JOptionPane.showMessageDialog(null, "Contador  "+contador + ", ¿se encontro? " + encontrado);

It should be noted that if the counter variable is initialized to 0, if palabra = "hola" and you write "t" which would be the comparison, you will obtain as a result the value of the variable contador 4, which are the occasions that the letter "t" in the word, variable encontrado will have value false .

If palabra = "hola" and write "a", the contador will obviously have a value of 3, which are the occasions that the letter "a" did not find, and the variable encontrado will have value true .

I add a online demo to see what I'm saying.

    
answered by 01.08.2017 в 02:42