我在尝试反转字符串时遇到 StringIndexOutOfBoundsException
我使用的是eclipse,异常(exception)的是
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:String index out of range: -1
at java.lang.String.charAt(UnknownSource)
at Abdo.Abdo.reverseRec(Abdo.java:13) at Abdo.Abdo.reverseRec(Abdo.java:15)
at Abdo.Abdo.reverseRec(Abdo.java:15) at Abdo.Abdo.main(Abdo.java:24)
这是我的代码:
public static String reverseRec (String s){
int max=s.length()-1;
String newstring ="";
if(s==null)
return "";
else{
newstring+=s.charAt(max);
s=s.substring(1,max);
return newstring + reverseRec(s);
}
}
public static void main (String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter string");
String s=sc.next();
System.out.println(reverseRec(s));
}
最佳答案
最大
可能是0
。
这是代码
public static String reverseRec (String s){
String newstring ="";
if(s==null || s.isEmpty())
return "";
else{
int max=s.length()-1;
newstring+=s.charAt(max);
s=s.substring(0,max);
return newstring + reverseRec(s);
}
}
关于java - 线程 "main"java.lang.StringIndexOutOfBoundsException : String index out of range: -1 中的错误异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23434733/