简体   繁体   中英

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

While trying to check Palindrome String getting this error"String Index out of bound -1"

public static void main(String[]args) {

    String s= "Madam";
    String Temp=s;
    String k=new String();
    //System.out.println(s.length());
    int m=s.length();

    for (int i=5;i>=m;m--) {
        System.out.println(m);
        String t=String.valueOf(s.charAt(m-1) ) ;
        k=k+t;
        System.out.println(k);
    }

    System.out.println(k);

    if (k==Temp) {
        System.out.println("String is Palindrome"+" "+k);   
    } else {
        System.out.println("String is not Palindrome"); 
    }
}

Remove this

for (int i=5;i>=m;m--)

with this

for (int i=s.length();i>0;i--)  
String t=String.valueOf(s.charAt(i-1) ) ;

because length of string is 5 in this case and then index range is 0-4 in this case and you are also accessing 0 index which will give you -1 at this place s.charAt(m-1) so don't traverse 0 index. plus there should be i-- with decrement operator instead of m--

or one line code can also be as

System.out.println(s.equals(new StringBuilder(s).reverse().toString()));
// this will give you boolean result with True or False
// which can be used with conditional statements to make thing concise and clean

but this will not too efficient when string is considerably very large

In the loop you want to use i , but dealing with m . Even you are decreasing m . Whenever m is decreased to 0, s.charAt(m-1) is trying to find character in negative position of the string. As a result, you are getting StringIndexOutOfBoundsException . So, instead of

for (int i=5;i>=m;m--) {
    System.out.println(m);
    String t=String.valueOf(s.charAt(m-1) ) ;
    k=k+t;
    System.out.println(k);
}

It should be:

for (int i = m-1; i >= 0; i--) {
    String t = String.valueOf(s.charAt(i)) ;
    k=k+t;
    System.out.println(k);
}

Simply the code could be:

String s = "Madam", reverse = "";
int m = s.length();

for (int i = m - 1; i >= 0; i--) {
    reverse += s.charAt(i);
}
System.out.println(reverse);

if (reverse.equalsIgnoreCase(s)) { // don't use '==' for checking equality of strings
    System.out.println(s + " is Palindrome");
} else {
    System.out.println(s + " is not Palindrome");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM