如何使Java中的循环增加1以外的增量

Tom*_*kie 68 java loops for-loop

如果您有这样的for循环:

for(j = 0; j<=90; j++){}
Run Code Online (Sandbox Code Playgroud)

它工作正常.但是当你有这样的for循环时:

for(j = 0; j<=90; j+3){}
Run Code Online (Sandbox Code Playgroud)

它不起作用.有人可以向我解释一下吗?

小智 105

那是因为j+3没有改变的价值j.你需要用j = j + 3或替换它,j += 3使得值j增加3:

for (j = 0; j <= 90; j += 3) { }
Run Code Online (Sandbox Code Playgroud)

  • @drachenstern换句话说,一个while循环. (6认同)
  • 或者他可以`int j = 0; for(; j <= 90;){... j + = 3;}`但这是非显而易见的`;)` (2认同)

jco*_*and 40

由于没有其他人真正解决过Could someone please explain this to me?我相信我会:

j++ 是简写,这不是一个实际的操作(确实是真的,但请耐心解释)

j++实际上是等于操作,j = j + 1;除了它不是宏或内联替换的东西.这里有很多关于这些操作i+++++i及其含义的讨论(因为它可以被解释为i++ + ++iOR(i++)++ + i

这让我们:i++对比++i.他们被称为post-incrementpre-increment运营商.你能猜出他们为什么这么命名吗?重要的部分是它们如何用于作业.例如,你可以这样做:j=i++;或者j=++i;我们现在做一个示例实验:

// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;

// yes we could have already set the value to 5 before, but I chose not to.
i = 5;

j = i++;
k = ++i;

print(i, j, k); 
//pretend this command prints them out nicely 
//to the console screen or something, it's an example
Run Code Online (Sandbox Code Playgroud)

i,j和k的值是多少?

我会给你答案,让你解决;)

i = 7, j = 5, k = 7;这是前后增量运算符的强大功能,以及使用它们的危险.但是这是编写相同操作顺序的另一种方式:

// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;

// yes we could have already set the value to 5 before, but I chose not to.
i = 5;

j = i;
i = i + 1; //post-increment

i = i + 1; //pre-increment
k = i;

print(i, j, k); 
//pretend this command prints them out nicely 
//to the console screen or something, it's an example
Run Code Online (Sandbox Code Playgroud)

好吧,既然我已经向你展示了++操作员的工作原理,那就让我们来看看它为什么不起作用了j+3......还记得我之前怎么称它为"速记"吗?这只是它,看到第二个例子,因为这是有效地使用该命令之前,什么编译器(它比这更复杂,但是这不是最初的解释).因此,您会看到"扩展速记"具有i =AND,i + 1这就是您的请求所具有的.

这可以追溯到数学.函数被定义在哪里f(x) = mx + b或一个等式,y = mx + b所以我们称之为mx + b...它当然不是函数或等式.最多只是表达.这就是j+3一个表达方式.没有赋值的表达式对我们没有好处,但它确实占用了CPU时间(假设编译器没有优化它).


我希望能为你澄清一些事情并给你一些提出新问题的空间.干杯!


Con*_*nor 9

在您的示例中,j+=3增量为3.

(这里没有什么可说的,如果它的语法相关我先建议谷歌搜索,但我是新来的,所以我可能是错的.)

  • 你是对的,但原来的问题是`j + 3`**实际上没有增加`j`.OP应该使用`j + = 3`. (3认同)

Abr*_*dam 7

for(j = 0; j<=90; j = j+3)
{

}
Run Code Online (Sandbox Code Playgroud)

j+3不会将新值赋给j,add j=j+3会将新值赋给j,循环将向上移动3.

j++就像说j = j+1,所以在这种情况下你将新值分配给j就像上面那样.


Ara*_*ram 6

更改

for(j = 0; j<=90; j+3)
Run Code Online (Sandbox Code Playgroud)

for(j = 0; j<=90; j=j+3)
Run Code Online (Sandbox Code Playgroud)