Error ""AWT-Eventqueue-0" java.lang.Stringindexoutofboundsexception: String index out of range: 0" in Java when trying to do IF

Asked

Viewed 923 times

1

I am making a condition in the execution of a search in Java, what happens is that I cannot have blank space, asterisk(*) or question mark(?) as the first character of the search. However Java is returning me 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)

Condition of line 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
        }
  • 1

    Wouldn’t that blow up the same way? Because if there is no char at position 0, when performing the method it would throw a stringindexoutofboundsexception, no?

  • 1

    @Pauloroberto as his suggestion in the first line avoids the exception? He will continue trying to access a position that does not exist. The only answer so far answers the question correctly.

  • Oops, sorry. I will post a better worded reply and delete my comment.

  • 1

    I posted an answer explaining better what I meant, it was very simple @Strokes

3 answers

2

The problem is that there is no char at position 0, as the string is empty. What you have to do is check before, to see if the String is empty or not. A 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.");
}
  • 2

    length(), because it is a method, not an attribute

  • sorry, I have not tested the code, I will edit the answer. Thank you!

  • 1

    Maybe you should take out the condition .equals(""), and put the error msg on the first if’s LSE, understood why?

  • Yes I understood, but I only did the initial if, I did not do an analysis of the code that OP posted.

  • yes, I only suggested, I even found that I was throbbing so much in yours that I ended up not holding and wrote a reply too, rs..

2


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

I noticed that you tried to do such validation through one of your if conditions:

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

But the exception is cast before your line of code even reaches the equals(""), because it happens in the charAt(0), so that line is useless. Instead, check the size of your String FIRST, and only 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
    }

View documentation StringIndexOutOfBoundsException and String length()

  • Testing

1

You can solve your problem by assigning ternary operator verification directly to the variable, so you don’t have to convert it and access it again to any verification, 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

Look how simple it turned out, and also note that I reversed the order of equals() to prevent errors if the variable to be compared was null, it is always best to use the equals() this way, always preventing NullPointerException's

Browser other questions tagged

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