Java charAt() String index out of range: 0

前端 未结 5 1159
刺人心
刺人心 2021-01-13 06:51

I have this code :

private void submitPstart() {

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


    }else          


        
相关标签:
5条回答
  • 2021-01-13 07:10

    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.

    0 讨论(0)
  • 2021-01-13 07:25

    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.

    0 讨论(0)
  • 2021-01-13 07:26

    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'){
    
    0 讨论(0)
  • 2021-01-13 07:26

    Add

    if (tStockPIStart!=null && tStockPIStart.length>0) {
        [...]
    }
    
    0 讨论(0)
  • 2021-01-13 07:37

    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.

    0 讨论(0)
提交回复
热议问题