user3597303
user3597303

Reputation: 1

Error Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

I am facing a StringIndexOutOfBoundsException while trying to reverse a string

I am using eclipse, the exception is

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)

Here is my code:

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));
}

Upvotes: 0

Views: 1542

Answers (1)

mashuai
mashuai

Reputation: 551

max maybe 0.
Here is the code

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);
    }
}

Upvotes: 2

Related Questions