我想做的是让我的代码将整数转换为以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
谢谢您的时间!
答案 0 :(得分:0)
因为它在a
循环中使用并增加了while (remainder > 0)
,而没有进行检查以确保a
仍为< convbases.length
。 (顺便说一句,它在一个地方convbases
,而在另一个地方convBases
,这应该阻止该代码甚至编译; Java区分大小写。)
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);
// ^^^^^^^^^^^^------------------------------------- using it
a++;
// ^^^^--------------------------------------------- incrementing it
}//end if
}//end while
}//end for
return convbases;
}//end streamChars
答案 1 :(得分:0)
在a达到colAvgs值之前,您的余数未设为0,然后,尝试访问convbases [a]崩溃。
您的while应当考虑a不能大于或等于colAvgs。
int size = colAvgs.length;
for (int a =0;a<size;a++)
{
remainder = colAvgs[a];
while(remainder>0 && a<size)
{
remainder = remainder%2;
if ((remainder%2)==0|| (remainder%2)==1)
{
convbases[a] = Integer.toString(remainder);
a++;
}//end if
}//end while
}//end for
if(remainder>0) //you know it finished due to a being too big.
else //this is what you want to happen
但是,我认为必须注意不要在for循环内修改循环变量是一个好习惯,因为这是for的工作的一部分。您不应该在while循环内执行a++
。当您确切知道循环将运行的迭代次数时,可以使用for循环。您在这里没有该信息。因此,您应该更改循环条件(在这种情况下,在启动for循环时为a<size
),或者改用while循环。