Limit anagram hits - Java

0

I have a code that checks if the user typed an existing word in the anagram, but if he types the same word 10 times it counts as 10 hits, I would like to limit this to 1 time only. The code I have done is this:

String palavra[] = {"BAR", "OLA", "ALO"}; // Maneira mais elegante de inicializar um vetor

String p = jTextField1.getText(); 

// Recupera String do componente textfield.

boolean existe = false; // Declaro uma flag que indica se encontrou ou não uma palavra igual.

for (int i = 0 ; i < 3; i++) {

    if (palavra[i].equals(p)) { // Percorre vetor de acordo com i.

        existe = true; // Altera valor da flag.

       break; // Sai do laço se encontrou palavra igual.
   }

}


if (existe==true) {

//verifica flag

    cont++;

JOptionPane.showMessageDialog(this, "Acertos :"+cont+"de 3");



} else if (existe==false){

    JOptionPane.showMessageDialog(this, "NAO EXISTE");
}
    
asked by anonymous 19.05.2015 / 05:22

1 answer

2

You have not posted the whole code, but let's assume it looks something like this:

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Anagramas extends JFrame {

    private JTextField jTextField1;
    private int cont;

    public Anagrama() {
        // ...
    }

    public void achaAnagrama() {
        String palavra[] = {"BAR", "OLA", "ALO"}; // Maneira mais elegante de inicializar um vetor

        String p = jTextField1.getText(); 

        // Recupera String do componente textfield.

        boolean existe = false; // Declaro uma flag que indica se encontrou ou não uma palavra igual.

        for (int i = 0 ; i < 3; i++) {

            if (palavra[i].equals(p)) { // Percorre vetor de acordo com i.

                existe = true; // Altera valor da flag.

               break; // Sai do laço se encontrou palavra igual.
           }

        }


        if (existe==true) {

        //verifica flag

            cont++;

        JOptionPane.showMessageDialog(this, "Acertos :"+cont+"de 3");



        } else if (existe==false){

            JOptionPane.showMessageDialog(this, "NAO EXISTE");
        }
    }

}

First thing I notice is that it is better to rename the array palavra to palavras in the plural, after all the array contains several words, not a single word.

By the way, which is better? Use String[] palavras or String palavras[] ? With String[] palavras we have the usual notation, variable type ( String[] ) followed by the name. Now with String palavras[] , we have the type defined by half ( String ), followed by the name of the variable, followed by something that will modify the type previously declared, something that is unnecessarily more complicated. Also, people who quickly roll their eyes at the code may not notice the [] after the variable name and imagine that the type is simply String instead of String[] . For this reason, it is best to state this:

String[] palavras = {"BAR", "OLA", "ALO"};

You can also simplify this:

if (existe == true) {
    // ...
} else if (existe == false) {
    // ...
}

Compare with == true is unnecessary. Simply using if (existe) { becomes clearer and simpler. Also, if it does not enter if , then the only possibility is that existe is false, so the test in else if is irrelevant because it will always be true when the flow reaches that point. So your code could be simplified to this:

if (existe) {
    // ...
} else {
    // ...
}

Another thing in your code is this:

for (int i = 0 ; i < 3; i++) {
// ...
JOptionPane.showMessageDialog(this, "Acertos :"+cont+"de 3");

Why 3? Because 3 is the size of your array . So it is better to compute the array size instead of using fixed 3, because in that case, if you decide to put more elements in array , you will not need to to sort the size manually:

for (int i = 0; i < palavras.length; i++) {
// ...
JOptionPane.showMessageDialog(this, "Acertos: " + cont + " de " + palavras.length);

And note also that there is space both before and after the "from" in the message.

In fact, we can even use the for-each syntax instead and get rid of the complexity of having to control the indexes in the iteration, further simplifying the code:

for (String pa : palavra) {
    if (pa.equals(p)) {
        existe = true; // Altera valor da flag.
        break; // Sai do laço se encontrou palavra igual.
   }
}

What you will need to know is not to count how many times he has hit, but what were the correct answers. After all, if he has already hit before and just repeated the word, you have to somewhere know what words were already tried. One way to do this is to save the right words in Set . And in this case, you will no longer need the cont variable, just use the Set size. This way, your code looks like this:

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Anagramas extends JFrame {

    private JTextField jTextField1;
    private Set<String> acertadas;

    public Anagrama() {
        // ...
        acertadas = new HashSet<>();
    }

    public void achaAnagrama() {
        String[] palavras = {"BAR", "OLA", "ALO"}; // Maneira mais elegante de inicializar um vetor

        String p = jTextField1.getText(); 

        // Recupera String do componente textfield.

        boolean existe = false; // Declaro uma flag que indica se encontrou ou não uma palavra igual.

        for (String pa : palavra) {
            if (pa.equals(p)) {
                existe = true; // Altera valor da flag.
                break; // Sai do laço se encontrou palavra igual.
            }
        }

        if (existe) {
            acertadas.add(p);
            JOptionPane.showMessageDialog(this, "Acertos: " + acertadas.size() + " de " + palavras.length);
        } else {
            JOptionPane.showMessageDialog(this, "NÃO EXISTE");
        }
    }
}

Can you do even better? Yes, it does. If palavras is also a Set , instead of an array , you can use the contains method and delete the loop as well as the existe variable, making the code very simple:

import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Anagramas extends JFrame {

    private JTextField jTextField1;
    private Set<String> acertadas;
    private Set<String> palavras;

    public Anagrama() {
        // ...
        acertadas = new HashSet<>();
        palavras = new HashSet<>(Arrays.asList("BAR", "OLA", "ALO"));
    }

    public void achaAnagrama() {
        String p = jTextField1.getText(); // Recupera String do componente textfield.

        if (palavras.contains(p)) {
            acertadas.add(p);
            JOptionPane.showMessageDialog(this, "Acertos: " + acertadas.size() + " de " + palavras.size());
        } else {
            JOptionPane.showMessageDialog(this, "NÃO EXISTE");
        }
    }
}
    
19.05.2015 / 07:01