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
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:
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
. When i
equals to (length - 1)
, str1.length()-1-i
equals to 0. Because of 0 < 1, Jvm throws new StringIndexOutOfBoundsException()
.
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.