简体   繁体   中英

Java charAt() String index out of range: 0

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

You need to check if getText() returns a 0-length (ie 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.

你必须检查null和长度大于0。

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

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.

Add

if (tStockPIStart!=null && tStockPIStart.length>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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM