java反转整数,但获取`StringIndexOutOfBoundsException`
我正试图写一个程序来反转以负号开始的整数。例如,如果数字为-123
,则输出应为-321
。但我得到了:
StringIndexOutOfBoundsException: String index out of range: 4
一致:
result += myString.charAt(i) + "";
代码的逻辑有什么问题
public class ReverseInteger {
public static void main(String[] args){
int x = -123;
String myString = Integer.toString(x);
String result = "";
if(myString.charAt(0) == '-'){
char sign = myString.charAt(0);
for(int i = myString.length(); i > 1; i--){
result += myString.charAt(i) + "";
}
result = sign + "" + result;
}
System.out.println(result);
}
}
# 1 楼答案
下面这一行似乎就是问题所在
将其更改为:
# 2 楼答案
这是因为你正在使用
String.length()
返回从1到X的长度。0表示空字符串你需要加-1
# 3 楼答案
在java中对
String
或数组进行索引是基于零的。这意味着索引0
是字符串中的第一个字符,而mystring.length() - 1
是字符串中的最后一个字符mystring.length()
在字符串的后面由于您在索引
mystring.length()
处访问数组,因此超出了数组的界限,因此出现了异常您想从索引
mystring.length() - 1
开始循环。此外,您还需要继续向下到索引1
,而不是像在循环中那样排除该索引就像这样: