How to make a functional string analysis method?

Asked

Viewed 152 times

0

I am creating an application that simulates a library system, and to begin with, you need to log in by entering a name in the text field. This is the method I created to parse the name (I want only uppercase letters and spaces in that string):

public boolean nomeConfere(String nome) {
    for(int n = 0; n < nome.length(); n++){
        if(nome.charAt(n) != 'A' || nome.charAt(n) != 'B' || nome.charAt(n) != 'C' || 
                nome.charAt(n) != 'D' || nome.charAt(n) != 'E' || nome.charAt(n) != 'F' || 
                nome.charAt(n) != 'G' || nome.charAt(n) != 'H' || nome.charAt(n) != 'I' || 
                nome.charAt(n) != 'J' || nome.charAt(n) != 'K' || nome.charAt(n) != 'L' || 
                nome.charAt(n) != 'M' || nome.charAt(n) != 'N' || nome.charAt(n) != 'O' || 
                nome.charAt(n) != 'P' || nome.charAt(n) != 'Q' || nome.charAt(n) != 'R' || 
                nome.charAt(n) != 'S' || nome.charAt(n) != 'T' || nome.charAt(n) != 'U' || 
                nome.charAt(n) != 'V' || nome.charAt(n) != 'W' || nome.charAt(n) != 'X' || 
                nome.charAt(n) != 'Y' || nome.charAt(n) != 'Z' || nome.charAt(n) != 'Ç' ||
                nome.charAt(n) != ' '){
            JOptionPane.showMessageDialog(null, "O nome não foi digitado corretamente.", "Erro", JOptionPane.ERROR_MESSAGE);
            return false;

        }
    }
    this.nome = nome; 
    return true;
}

But it’s not working. I tested the application after implementing it and put a name only with these characters in the text field, but the Joptionpane error that should not appear appeared appeared. Some solution?

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

2 answers

1

The problem is that you are using OR in condition. That is, if the name is different from A or different from B ...

Consider that the name is ADAO.

"A" != "A": false
"A" != "B": true

The comparison with C is not even performed because false || true results in true.

You can solve this by switching to AND instead of OR. So only if all conditions are true will your block run.

If you want to leave the code more lean you can use Regular Expressions to make this check.

1

Using regular expression your code will be simpler and easier to maintain. It would look like this:

public Boolean nomeConfere(String nome) {
  if (!nome.matches("^[A-Z ]+$")) {
    JOptionPane.showMessageDialog(null, "O nome não foi digitado corretamente.", "Erro", JOptionPane.ERROR_MESSAGE);
    return false;
  }

  return true;
}

The above regular expression tests if the String has characters from A to Z uppercase or spaces from start to finish.

Browser other questions tagged

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