有問題的問題是識別字串是否有逗號并從原始字串輸出子字串。
這是我的代碼:
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String fullString = "";
int checkForComma = 0;
String firstSubstring = "";
String secondSubstring = "";
boolean checkForInput = false;
while (!checkForInput) {
System.out.println("Enter input string: ");
fullString = scnr.nextLine();
if (fullString.equals("q")) {
checkForInput = true;
}
else {
checkForComma = fullString.indexOf(',');
if (checkForComma == -1) {
System.out.println("Error: No comma in string");
fullString = scnr.nextLine();
}
else {
continue;
}
firstSubstring = fullString.substring(0, checkForComma);
secondSubstring = fullString.substring(checkForComma 1, fullString.length());
System.out.println("First word: " firstSubstring);
System.out.println("Second word: " secondSubstring);
System.out.println();
System.out.println();
}
}
return;
}
}
我編譯時不斷收到的錯誤是:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 10
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
at java.base/java.lang.String.substring(String.java:1874)
at ParseStrings.main(ParseStrings.java:34)
我對編程還是有點陌生??,以前從未見過這種型別的錯誤,有什么方法可以解決這個問題,可能是什么原因造成的?
uj5u.com熱心網友回復:
當索引超出范圍時會發生例外。 什么是 StringIndexOutOfBoundsException?我該如何解決?
對于您的代碼,您不會重新初始化變數 checkForComma 的值
if (checkForComma == -1)
{
System.out.println("Error: No comma in string");
fullString = scnr.nextLine();
}
如果 checkForComma=-1,它將接受下一個輸入并跳轉到
firstSubstring = fullString.substring(0, checkForComma);
字串索引不能為 -1/negative,因此它會顯示錯誤。
錯誤的解決方案
您應該根據您的程式攝入重新初始化 checkForComma 的值,但不要讓它超過變數的范圍fullString。
uj5u.com熱心網友回復:
continue當您檢查 checkForComma 變數是否等于 -1 時,您無需在 else中使用,而是可以直接使用當 checkForComma 具有實際值時應運行的所有其他代碼。
只需替換這部分代碼即可。
checkForComma = fullString.indexOf(',');
if (checkForComma == -1) {
System.out.println("Error: No comma in string");
fullString = scnr.nextLine();
}
else {
firstSubstring = fullString.substring(0, checkForComma);
secondSubstring = fullString.substring(checkForComma 1);
System.out.println("First word: " firstSubstring);
System.out.println("Second word: " secondSubstring);
System.out.println();
System.out.println();
}
并且要獲得第二個單詞,您只能使用checkForComma 1在這種情況下的開始輸入,因為這將回傳值直到字串末尾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374139.html
