猿问

为什么这个 for 循环会遇到 ArrayIndexOtOfBounds 错误?

我想做的是让我的代码将整数转换为基数 2,然后将这些值转换为字符串数组中的元素。我试图避免使用 Integer.toBinary()。如果我能得到一些帮助,那将非常有帮助。


public String[] streamChars(int[] colAvgs)

{

 String avgString = Arrays.toString(colAvgs);

 String convBases[] = avgString.split(",");

 int remainder;

 for (int a =0;a<colAvgs.length;a++)

 {

  remainder = colAvgs[a];

   while(remainder>0)

    {

     remainder = remainder%2;

     if ((remainder%2)==0|| (remainder%2)==1)

      {

       convbases[a] = Integer.toString(remainder);

       a++;

      }//end if

    }//end while

 }//end for

return convbases;

}//end streamChars

感谢您的时间!


白板的微信
浏览 144回答 2
2回答

aluckdog

在 a 达到 colAvgs 值之前,余数不会变为 0,之后尝试访问 convbases[a] 会崩溃。您的 while 应考虑到 a 不能高于或等于 colAvgs。int size = colAvgs.length;for (int a =0;a<size;a++)&nbsp;{&nbsp; remainder = colAvgs[a];&nbsp; &nbsp;while(remainder>0 && a<size)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp;remainder = remainder%2;&nbsp; &nbsp; &nbsp;if ((remainder%2)==0|| (remainder%2)==1)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;convbases[a] = Integer.toString(remainder);&nbsp; &nbsp; &nbsp; &nbsp;a++;&nbsp; &nbsp; &nbsp; }//end if&nbsp; &nbsp; }//end while&nbsp;}//end forif(remainder>0) //you know it finished due to a being too big.else //this is what you want to happen但是,我认为重要的是要注意,最好不要修改 for 循环内的循环变量,因为这是 for 工作的一部分。您不应该a++在 while 循环内执行此操作。当您确切知道循环将运行的迭代次数时,可以使用 for 循环。你这里没有这些信息。因此,您应该更改循环条件(在本例a<size中是启动 for 循环时),或者改用 while 循环。

缥缈止盈

因为它a在while (remainder > 0)循环内使用并增加,而无需检查以确保a仍然存在< convbases.length。(顺便说一句,它convbases在一个地方,但convBases在另一个地方,这应该会阻止该代码编译;Java 区分大小写。)public String[] streamChars(int[] colAvgs){&nbsp;String avgString = Arrays.toString(colAvgs);&nbsp;String convBases[] = avgString.split(",");&nbsp;int remainder;&nbsp;for (int a =0;a<colAvgs.length;a++)&nbsp;{&nbsp; remainder = colAvgs[a];&nbsp; &nbsp;while(remainder>0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp;remainder = remainder%2;&nbsp; &nbsp; &nbsp;if ((remainder%2)==0|| (remainder%2)==1)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;convbases[a] = Integer.toString(remainder);//&nbsp; &nbsp; &nbsp;^^^^^^^^^^^^------------------------------------- using it&nbsp; &nbsp; &nbsp; &nbsp;a++;//&nbsp; &nbsp; &nbsp;^^^^--------------------------------------------- incrementing it&nbsp; &nbsp; &nbsp; }//end if&nbsp; &nbsp; }//end while&nbsp;}//end forreturn convbases;}//end streamChars
随时随地看视频慕课网APP

相关分类

Java
我要回答