gpt4 book ai didi

java - 为什么我收到 java.lang.StringIndexOutOfBounds 异常?

转载 作者:行者123 更新时间:2023-12-01 08:46:05 26 4
gpt4 key购买 nike

我有一个程序,它接受两个字符串参数,并根据它们的索引将它们视为 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);
}

最佳答案

让我们看看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 < 1, Jvm 抛出 new StringIndexOutOfBoundsException()

关于java - 为什么我收到 java.lang.StringIndexOutOfBounds 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43028964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com