[英]Why I am getting java.lang.StringIndexOutOfBounds Exception?
I have a program which is taking two String parameters and treating them as int's according to their indexes and try to do addition like we do on the paper but I am getting java.lang.StringOutOfBounds Exception , I couldn't solve it any help is appreciated Thanks in advance 我有一个程序使用两个String参数,并根据它们的索引将它们视为int,并尝试像在纸上一样进行加法操作,但是我遇到了java.lang.StringOutOfBounds Exception,我无法解决任何帮助是提前感谢
import java.util.Arrays;
public class Algorithm {
boolean flag=false;
public void topla(String str1,String str2){
String temp="";
int sum1=0,sum2=0;
String sonuc1="";
if(str2.length()>str1.length()){
temp=str1;
str1=str2;
str2=temp;
}
for (int i=0; i<str1.length(); i++)
{
sum1 = Integer.parseInt(str1.substring(str1.length()-1-i, 1));
sum2=0;
if(str2.length()-i>0){
sum2=Integer.parseInt(str2.substring(str2.length()-1-i,1));
}
else
sum2 = 0;
sum1 = sum1 + sum2;
if(flag)
{
sum1 += 1;
flag = false;
}
if (sum1 > 9)
{
flag = true;
sum1 -= 10;
}
sonuc1 += sum1;
}
char[] sonucu_duzelt = sonuc1.toCharArray();
String string =new String(sonucu_duzelt);
System.out.println(string);
}
Lets have a look at substring
method's implementation: 让我们看
substring
方法的实现:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
And this code is important for you: 此代码对您很重要:
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
You must change your below lines: 您必须更改以下几行:
Integer.parseInt(str1.substring(str1.length()-1-i, 1));
Integer.parseInt(str2.substring(str2.length()-1-i,1));
str1.length()-1-i
can't be greater than 1
. str1.length()-1-i
不能大于1
。 When i
equals to (length - 1)
, str1.length()-1-i
equals to 0. Because of 0 < 1, Jvm throws new StringIndexOutOfBoundsException()
. 当
i
等于(length - 1)
, str1.length()-1-i
等于0。由于0 <1,Jvm抛出new StringIndexOutOfBoundsException()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.