我正在做一个家庭作业,程序的关键循环给我带来了麻烦。我的老师告诉我,如果我对反控制变量使用while循环,她会扣分,所以我急于把这件事做好。
下面是我想要做的事情,以及我内心感受到的应该做的事情:
for ( int check = 0; check == value; check++ ) {
int octal = getOctal();
int decimal = convertOctal( octal );
System.out.printf( "%d:%d", octal, decimal );
}但是,此循环不会运行。我试着用一个while循环来做这件事,它完美地工作了!
int check = 0;
while ( check < value )
{
int octal = getOctal();
int decimal = convertOctal( octal );
System.out.printf( "%d:%d", octal, decimal );
check++;
}下面是main方法的其余部分:
public static void main ( String args[] )
{
int value = getCount();
while ( value < 0 )
{
System.out.print( "\nYou must enter a positive number" );
value = getCount();
}
if ( value == 0 )
{
System.out.print( "\n\nNo numbers to convert.\n\n" );
}
else
{
int check = 0;
while ( check < value )
{
int octal = getOctal();
int decimal = convertOctal( octal );
System.out.printf( "%d:%d", octal, decimal );
check++;
}
}
}是的,这是一个八进制到十进制的转换器。我自己从头开始编写了转换器方法,并对此感到非常自豪。
编辑:我的问题是,这里出了什么问题?编辑第二部分:感谢大家的帮助,澄清了我的误解。转到方法文档!
发布于 2013-03-28 04:07:04
for ( int check = 0; check == value; check++ )这将仅在check == value的情况下运行。修改为:
for ( int check = 0; check < value; check++ )发布于 2013-03-28 04:06:32
尝试for ( int check = 0; check <= value; check++ )而不是for ( int check = 0; check == value; check++ )
发布于 2013-03-28 04:13:23
来自the Oracle website (我的重点):
语句提供了一种循环遍历一系列值的紧凑方法。程序员通常将其称为"for循环“,因为它反复循环直到满足特定条件。for语句的一般形式可以表示为:
for (initialization; termination; increment) {
statement(s)
} 在使用此版本的for语句时,请记住:
初始化表达式初始化循环;它在循环开始时执行一次。
当终止表达式的计算结果为false时,循环将终止。
在循环中的每次迭代之后都会调用增量表达式;该表达式递增或递减值是完全可以接受的。
https://stackoverflow.com/questions/15668378
复制相似问题