我尝试编写逻辑来打印给定字符串是否是其他字符串的排列,
发生运行时错误
"java.lang.ArrayIndexOutOfBoundsException"
我只访问了字符串数组的两个索引。
->给定的字符串由两个空格分隔。
public static String permute(String str){
String[] st=str.split("\\s+");
String sr1=st[0].toString();//Run time error
String sr2=st[1].toString();
}
Run Time Error Msg: "java.lang.ArrayIndexOutOfBoundsException"
请帮助解决此错误。
最佳答案
您的代码的问题在于您假设您将在数组中获得两个项目,但并非所有输入都是如此。 您应该考虑数组大小:
public static String permute(String str){
String[] st=str.split("\\s+");
for (String item : st) {
// do whatever
}
}
如果您只想处理前两项,而不管是否还有更多,请执行类似 for (int i = 0 ; i < st.length && i < 2 ; i++)
的操作,但在访问数组项之前始终验证数组的长度
关于java - 使用超出范围的索引拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57018420/