我有一个程序,它接受两个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);
}
答案 0 :(得分:1)
让我们看一下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);
}
此代码对您很重要:
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
您必须更改以下行:
Integer.parseInt(str1.substring(str1.length()-1-i, 1));
Integer.parseInt(str2.substring(str2.length()-1-i,1));
str1.length()-1-i
不能大于1
。当i
等于(length - 1)
时,str1.length()-1-i
等于0.因为0&lt; 1,Jvm抛出new StringIndexOutOfBoundsException()
。