5

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

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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'){

4 Comments

what if sir for example I enter a lower case letter and want it to conver to upper case?
you can do two thing 1. add lower case condition or 2. use equalsignorecase.
if (tStockPIStart!=null && tStockPIStart.getText().length()>0 && "A".equalsIgnoreCase(""+tStockPIStart.getText().charAt(0)) && "Z".equalsIgnoreCase(""+tStockPIStart.getText().charAt(0))){}
I think it would make life easier if tStockPIStart.getText() was extracted into a variable
2

Try

if (tStockPIStart.getText().length() > 0 && tStockPIStart.getText().charAt(0)>='A' && tStockPIStart.getText().charAt(0)<='Z')

In your case, if the text is empty, then the length returned will be 0. Hence the charAt(..) method will throw you an exception. As such, you should first check that the text that you're trying to compare is empty or not.

2 Comments

thanks for this sir. i also tried this one and its working :)
what if sir for example I enter a lower case letter and want it to conver to upper case?
2

Add

if (tStockPIStart!=null && tStockPIStart.length>0) {
    [...]
}

Comments

0

In Java 7 there is the isEmpty method you can use to make things a bit more expressive in your code

if (tStockPIStart.getText()!=null && !tStockPIStart.getText().isEmpty()) {
    //do stuff
}

This is the same as doing length != 0 but I personally think is a bit more clear.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.