我每次尝试编译异常时都会遇到代码问题 java.lang.StringIndexOutOfBoundsException
出现。这是有问题的代码我真的不知道我做错了什么。在代码中,我尝试使用某些条件拆分 string
,string
表示多项式。
int[] coef1= new int[20];
for(i=0;i<polinom.length()+1;i++){
if(polinom.charAt(i)=='+' )
c=polinom.charAt(i+1);
else{
if(polinom.charAt(i)=='^'){
v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
coef1[v]=Integer.parseInt(Character.toString(c));
System.out.print(coef1[v]);
}
}
}
for(i=0;i<polinom.length()+1;i++){
if(polinom.charAt(i)=='-' )
c=polinom.charAt(i+1);
else{
if(polinom.charAt(i)=='^'){
v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
coef1[v]=-Integer.parseInt(Character.toString(c));
System.out.print(coef1[v]);
}
}
}
这里是异常 if(polinom.charAt(i)=='+' )
最佳答案
只需更换所有
for(i=0;i<polinom.length()+1;i++){
与
for(i=0;i<polinom.length()-1;i++){
由于索引是从 0 开始的并且您使用 polinom.charAt(i+1)
,因此 i+1
永远不应等于(也不大于) polinom.length
.
或者,如果您希望在字符串的最后一个字符之前进行测试(用于其他处理),您可以确保 polinom.charAt(i+1)
永远不会被触发,如果 i == polinom.length() - 1
,在处理你的东西之前添加一个测试:
for(i=0;i<polinom.length();i++){ // not using -1, looping to the end of the string
if(polinom.charAt(i)=='+' && i < polinom.length() - 1) // checking that no exception will be thrown
c=polinom.charAt(i+1);
else{
if(polinom.charAt(i)=='^' && i < polinom.length() - 1){ // same
v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
coef1[v]=-Integer.parseInt(Character.toString(c));
System.out.print(coef1[v]);
}
}
}
关于Java 异常 : java. lang.StringIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35774671/