Error "" AWT-EventQueue-0 "java.lang.StringIndexOutOfBoundsException: String index out of range: 0" in Java when trying to make IF

1

I'm doing a condition in running a search in Java, what happens is that I can not have whitespace, asterisk (*) or question mark (?) as the first character of the search. But Java is returning the following error when I leave the field blank:

Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(Unknown Source)
    at main.Princ$4.actionPerformed(Princ.java:255)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Line Condition 255:

        if (Character.toString(txtConteudo.getText().charAt(0))
                        .equals(" ")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("?")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("*")) {
            JOptionPane
                    .showMessageDialog(
                            panel,
                            "O campo de busca não pode estar vazio ou possuir \"?\", \"*\" ou espaço em branco como primeiro caracter.");

        } else {
            // executa a busca
        }
    
asked by anonymous 20.03.2014 / 12:42

3 answers

2

The size of your string returned by the txtConteudo.getText() operation has 0 size, and you try to access its first element through the txtConteudo.getText().charAt(0) command, that is, you are trying to access a character beyond the last valid character. In fact you do not even have one character and you try to access the first one, so an exception is thrown.

I noticed that you tried to validate through one of your if conditions:

Character.toString(txtConteudo.getText().charAt(0)).equals("")

But the exception is thrown even before your line of code gets to equals("") , since it happens in charAt(0) , so this line is useless. Instead, check the size of your String BEFORE everything, and then try to access its characters.

Example:

    if(txtConteudo.getText().length() == 0 //graças ao short-circuit não compara as demais se essa condição é falsa
       || Character.toString(txtConteudo.getText().charAt(0)).equals(" ")
       || Character.toString(txtConteudo.getText().charAt(0)).equals("?")
       || Character.toString(txtConteudo.getText().charAt(0)).equals("*")) {

        JOptionPane.showMessageDialog(panel,
           "O campo de busca não pode estar vazio ou possuir \"?\", \"*\" ou espaço em branco como primeiro caracter.");
    } else {
        // executa a busca
    }

See the StringIndexOutOfBoundsException documentation and String length ()

    
20.03.2014 / 13:35
2

The problem is that there is no char at position 0 because the String is empty. What you have to do is check beforehand to see if the String is empty or not. One possible example:

if(txtConteudo.getText().length() > 0){
        if (Character.toString(txtConteudo.getText().charAt(0))
                        .equals(" ")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("?")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("*")) {
            JOptionPane
                    .showMessageDialog(
                            panel,
                            "O campo de busca não pode estar vazio ou possuir \"?\", \"*\" ou espaço em branco como primeiro caracter.");

        } else {
            // executa a busca
        }
}else
{
JOptionPane.showMessageDialog( panel,
                                "O campo de busca não pode estar vazio.");
}
    
20.03.2014 / 12:48
1

You can solve your problem with ternary operator verification assigned directly to the variable, so you do not have to convert it and re-access it at all times, saving unnecessary code and performance:

//compare vai receber o txtConteudo na 0 se length for > 0 senão recebe ""
String compare = (txtConteudo.getText().length() > 0) ? Character.toString(txtConteudo.getText().charAt(0)) : "";
if (" ".equals(compare) || ("").equals(compare) || "?".equals(compare) || "*".equals(compare))
  JOptionPane.showMessageDialog(panel, "O campo de busca não pode estar vazio ou possuir \"?\", \"*\" ou espaço em branco como primeiro caracter.");
else
  // executa a busca

See how simple it was, and also note that I inverted the order of equals() to prevent errors if the variable being compared was null, it is always better to use equals() in this way, always preventing NullPointerException 's

    
20.03.2014 / 13:50