How to make a functional string parsing method?

0

I'm 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 this 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 is not working. I tested the application after implementing it and put a name with only those characters in the text field, but the error JOptionPane that should not appear appeared. Any solution?

    
asked by anonymous 07.11.2016 / 09:46

2 answers

1

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

Consider that the name is ADAO.

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

The comparison with C is neither performed, because false || true results in true .

You can solve this by changing to AND rather than OR. So only if all conditions are true will your block be executed.

If you want to make the code leaner, you can use Regular Expressions to do this verification.

    
07.11.2016 / 10:31
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 whether the String has uppercase characters from A to Z or spaces from beginning to end.

    
07.11.2016 / 11:55