[英]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"在尝试检查回文字符串时出现此错误“字符串索引超出范围 -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.因为在这种情况下字符串的长度是 5,然后在这种情况下索引范围是 0-4,并且您还访问了 0 索引,这将在此位置为您提供 -1
s.charAt(m-1)
所以不要遍历 0指数。 plus there should be i--
with decrement operator instead of m--
加上应该有
i--
用递减运算符而不是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
.在循环中你想使用
i
,但处理m
。 Even you are decreasing m
.即使你正在减少
m
。 Whenever m is decreased to 0, s.charAt(m-1)
is trying to find character in negative position of the string.每当 m 减少到 0 时,
s.charAt(m-1)
就会尝试在字符串的负数位置查找字符。 As a result, you are getting StringIndexOutOfBoundsException
.结果,您收到
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.