Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java charAt() String index out of range: 0

Tags:

java

I have this code :

private void submitPstart() {

    if (tStock.getText().charAt(0)>='A' && tStock.getText().charAt(0)<='Z'){


    }else {
        errorBox ("Uppercase A-Z");
    }

    tStock.setText("");
    tStock.setFocus();
}

THis is working but when I try not to put anything on the textbox and press the OK button it crashes. It says:

java.lang.StringIndexOutOfBoundsException: String index out of range: 0

and it pointed out to this part: if (tStock.getText().charAt(0)>='A' && tStock.getText().charAt(0)<='Z')

Any help is appreciated. Thanks

like image 711
user1782426 Avatar asked Oct 29 '12 09:10

user1782426


People also ask

How do I fix string 0 out of range?

To resolve the problem, simply remove any offending instances of unnecessary letters/symbols or words which do not belong in the mappings file.

Is charAt 0 indexed?

Definition and Usage. The charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

What does charAt 0 do in Java?

charAt(0). This returns the first character in our string. In other words, we retrieve the character with the index value 0. In this case, the charAt() method returned the character G.

What is meant by charAt i )-' 0?

charAt(i) will return a character and string. charAt(i)- '0' will return the actual integer value. For e.g. string="12345",this method will return an integer array [1,2,3,4,5].


2 Answers

You need to check if getText() returns a 0-length (i.e. empty) string.

If it does, then don't try to pull the first character out! (via charAt())

Note that your commented-out check for length() should occur prior to the existing character check.

You may want to check for a null string being returned as well, depending on your framework/solution etc. Note the Apache Commons StringUtils.isEmpty() method, which performs this check concisely.

like image 71
Brian Agnew Avatar answered Oct 30 '22 19:10

Brian Agnew


you must check null and length greater than 0.

 if (tStockPIStart!=null && tStockPIStart.getText().length()>0 && tStockPIStart.getText().charAt(0)>='A' && tStockPIStart.getText().charAt(0)<='Z'){
like image 45
Subhrajyoti Majumder Avatar answered Oct 30 '22 20:10

Subhrajyoti Majumder