java - 如何修复异常 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()
方法,但它仍然给了我同样的例外。
如何解决?
解决方案
s2 = s1.substring(0, 26).trim();
如果 s1 的长度小于 26,就会发生这种情况。首先,您需要检查 的长度,s1
然后您可以substring()
根据 的长度应用该方法s1
。
推荐阅读
- c++ - C++中的箭头检测
- r - 如何使用带有 if 条件的 NA 替换日期列
- python - 如何在 Pandas DataFrame 中只保留最小值
- javascript - twitch api获取令牌返回“未知错误”Angular
- c# - 如何将 IMethodSymbol 转换为 MethodDeclarationSyntax?
- vue.js - Vue JS无线电输入“已检查”不适用于v-model
- mysql - 如果重复记录,是否可以进行 MySQL SELECT 查询来更改记录?
- javascript - 在 () -> fn 上传递对 onClick 的引用是否对性能有真正的影响?在反应
- matplotlib - 使用 matplotlib,有没有办法创建基本不等式的简单二维图
- python - 使用电子邮件收集功能制作基于 python 的网站,但在输入电子邮件时崩溃