让人迷糊的String index out of Range??新手求解

dround 2009-05-18 09:09:07

public int Run(String s)
{
int len = s.length(); //字符串长度len
int n=0;
int i=1;

for (i=1;i<=len;i++)
{
if (s.charAt(i)=='+'||s.charAt(i)=='-'||s.charAt(i)=='*'||s.charAt(i)=='/')
{n=n+1;}
}
int factor[] =new int[n+1]; //每个运算因子作为一个factor存在
int act[] = new int[n]; //运算符号99个


int posa=1;int posb=1; //截取位置符

int fi=1;int ai=1; //运算因子号数,运算符号号数
int ans=0;
i=1;
for (i=1;i<=len;i++) //提取运算因子和运算符号循环
{
char temps = s.charAt(i); //当前指针符
if (temps =='+'||temps=='-'||temps=='*'||temps=='/')
{
posb=i-1;
factor[fi]=Integer.parseInt(s.substring(posa,posb)); //提取运算因子
posa=i+1;
fi=fi+1;


if (temps == '+'){act[ai]=1;}
else if (temps == '-'){act[ai]=2;}
else if (temps == '*'){act[ai]=3;}
else if (temps == '/'){act[ai]=4;}

ai=ai+1;
}
}

ans=factor[1];

if(ai!=1){
for (i=2;i<=ai+1;i++) //运算循环
{
if (act[i-1] == 1){ans=ans+factor[i];}
else if (act[i-1] == 2){ans=ans-factor[i];}
else if (act[i-1] == 3){ans=ans*factor[i];}
else if (act[i-1] == 4){ans=ans/factor[i];}
}
}
return ans;
}


目标:是调用Run函数,输入一个字符串例如"213+123*567-234/35",返回一个答案ans;

当输入上述例子提示: StringIndexOutOfBoundsException: String index out of range: 18

求解??万分感谢
...全文
1370 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
dround 2009-05-18
  • 打赏
  • 举报
回复
源文件改了很多,所以现在也试不了了,不过Index从0开始倒是没错,我这种新手很容易忽略
licao88 2009-05-18
  • 打赏
  • 举报
回复
学习下
dround 2009-05-18
  • 打赏
  • 举报
回复
噢,对··· 刚看了看说明,是从0开始,刚刚又换了个方法,等下试试
knightzhuwei 2009-05-18
  • 打赏
  • 举报
回复
i<=len 改为<吧 索引是从0开始的 len是取不到的

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧