Java 循环递增正整数
这个程序只是持续运行很长时间,什么也不输出。我哪里出了问题,有人发现了吗 我只需要它来生成1到10之间的偶数Java 循环递增正整数,java,loops,if-statement,while-loop,Java,Loops,If Statement,While Loop,这个程序只是持续运行很长时间,什么也不输出。我哪里出了问题,有人发现了吗 我只需要它来生成1到10之间的偶数 class EvenLoop { public static void main(String[] args) { int i = 1; int limit = 10; while( i <limit) { if(i % 2==0) { System.out.println("i = " + i)
class EvenLoop {
public static void main(String[] args) {
int i = 1;
int limit = 10;
while( i <limit)
{
if(i % 2==0)
{
System.out.println("i = " + i);
i++;
}
}
}
将i++从if语句中去掉,因为i保持为1,所以它会以内联方式运行
while( i <limit)
{
if(i % 2==0)
{
System.out.println("i = " + i);
}
i++;
}
将i++放在while循环内部和if条件外部,以避免无限循环
public static void main(String[] args) {
int i = 1;
int limit = 10;
while( i <limit)
{
if(i % 2==0)
{
System.out.println("i = " + i);
}
i++; // put i++ inside while loop and outside of if
}
}
你在循环,直到我达到一个特定的极限,但是你只在循环中增加i,如果它可以除以2。所以它将无限地停留在第一个不能被2整除的数字上,因为它永远不会增加。您可能希望增量i++在if之外
您正在if语句中递增“i”
您从1开始&将永远不会输入if to increment i.几乎没有如下更正:
class EvenLoop {
public static void main(String[] args) {
int i = 1;
int limit = 10;
while (i < limit) {
if (i % 2 == 0) {
System.out.println("i = " + i);
}
i++;//outside if
}
}
}// missing closing bracket
公共类循环{
公共静态无效字符串[]args{
int start=1;
整数极限=10;
对于int i=start+start%2;我将i++从if循环中取出,将i++从if块中取出。
class EvenLoop {
public static void main(String[] args) {
int i = 1;
int limit = 10;
while (i < limit) {
if (i % 2 == 0) {
System.out.println("i = " + i);
}
i++;//outside if
}
}
}// missing closing bracket