首页 > 解决方案 > 如何修复异常 java.lang.StringIndexOutOfBoundsException?

问题描述

这是我的代码:

public VerifyTopicNotificationPage timeOfReceivedTopic()
{
    Date objDate = new Date(); // Current System Date and time is assigned to objDate
    SimpleDateFormat sdf;
    sdf = new SimpleDateFormat("E, MM dd, yyyy hh:mm");
    String dateString = sdf.format(objDate);
    System.out.println("Date in the format : "+dateString);
    Date dateObject = new Date();
    System.out.println("Syshour is : " + objDate.getHours() + "  " + "SysMin is : " + objDate.getMinutes());
    //try for notification
    int counter=0;
    Boolean flag=false;
    while((counter<10)&&(!flag)) {
        driver.navigate().refresh();
        seleniumUtil.explicitWait(2000);
        seleniumUtil.clickElement(clickOnBellIcon);
        seleniumUtil.explicitWait(4000);
        String s1="";
        String s2="";
        try {
           s1 = (driver.findElement(By.xpath("/html/body/div[3]/div/div/div/div[2]/div[2]/span")).getText())+(" ");
           s2 = s1.substring(0, 26).trim();
           System.out.println("Substring is " + s2);
           SimpleDateFormat format2 = new SimpleDateFormat("EEE, MMM dd, yyyy hh:mm a", Locale.US);
           Date date1 = null;
           try {
                date1 = format2.parse(s2);
                System.out.println("UI Date is : " + date1);
                System.out.println("UI hour is : " + date1.getHours());
                System.out.println("UI min is : " + date1.getMinutes());
           } catch (ParseException e) {
                e.printStackTrace();
            }
            if ((dateObject.getHours()==(date1.getHours())))
            {
                if (((dateObject.getMinutes() <= date1.getMinutes()) && (dateObject.getMinutes() <= dateObject.getMinutes()+10)) || ((dateObject.getMinutes() >= date1.getMinutes()) && (dateObject.getMinutes() >= dateObject.getMinutes()+10))) //3.55 -> 4.03 | 3.58
                {
                    System.out.println("Match found at " + s2);
                    flag = true;
                    break;
                }
            }
        }
        catch(Exception e)
        {
            System.out.println("encountered exception " + e);
        }
        counter++;
        seleniumUtil.explicitWait(60000);
    }
    Assert.assertTrue(flag);
    return PageFactory.initElements(driver, VerifyTopicNotificationPage.class);
}

我的代码结果:

Date in the format : Tue, 02 02, 2021 09:45
Syshour is : 9  SysMin is : 45
encountered exception java.lang.StringIndexOutOfBoundsException: String index out of range: 26

我尝试使用trim()方法,但它仍然给了我同样的例外。
如何解决?

标签: javastringindexoutofboundsexception

解决方案


s2 = s1.substring(0, 26).trim();

如果 s1 的长度小于 26,就会发生这种情况。首先,您需要检查 的长度,s1然后您可以substring()根据 的长度应用该方法s1


推荐阅读