[英]Constant StringIndexOutOfBoundsException
我正在准備即將進行的測試,並試圖了解子字符串的工作原理。 請向我解釋,因為我實際上沒有在線獲得解釋。 我的錯誤是:StringIndexOutOfBounds異常我不明白它是如何導致錯誤的,因為在調用子字符串提取字符串時,它將自動從endIndex -1。 那就是為什么我加1,但它不起作用。
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.print("Enter the string: ");
String string = scn.nextLine();
System.out.print("Enter the start char: ");
char startChar = scn.next().charAt(0);
System.out.print("Enter the end char: ");
char endChar = scn.next().charAt(string.length() - 1);
int startIndex = string.indexOf(startChar); //Get index of the start character
int endIndex = string.indexOf(endChar);
if(startIndex == -1) {
System.out.println("No such substring"); //First char doesn't exist
}
else {
if(endIndex == -1) {
System.out.println("No such substring");
}
else {
String extractedString = string.substring(startIndex, endIndex + 1); //Cause sub string is -1
System.out.println("Substring [" + extractedString + "]" + " is found");
}
}
應該
char endChar = scn.next().charAt(0);
因此,您要做的就是調用scn.next()
,並從該scn.next()
調用中scn.next()
string.length-1
的char。 string
多久了, scn.next()
多久了?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.