for循环如何在Java中检查其条件? [英] How does a for loop check its conditions in Java?

查看:173
本文介绍了for循环如何在Java中检查其条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与java中检查for循环的条件的顺序有关,因为在循环的conditions中有语句 。这似乎是一个不切实际的事情(我从来没有见过它以任何实际的方式使用),尽管我对打印的内容缺乏了解,但是我认为我可能不完全理解for循环的功能。以下问题出现在最近的考试中:

以下方法用n = 5的输入打印什么?


$ b $ (int n){
for(int i = -1; i< n; System.out.print(i +)); public static void mystery ){
我++;




$ b $ p $正确答案是:
0 1 2 3 4 5



对我来说,循环似乎应该打印-1,然后增加1,打印0 .....直到i = 4然后打印4,将i递增1,并在循环的条件下跳出循环i < ñ。
为什么是正确的答案是什么,为什么我的逻辑有缺陷?
解决方案

初始化表达式发生一次。然后检查条件,然后循环的主体发生,然后增量表达式发生(您的 print 语句),然后我们重新开始。



官方教程是很明显,如果你仔细阅读。



语句中的的Java语言规范条目也可能是有趣的,如果你想要完整的细节。

My question has to do with the order in which java checks the conditions of a for loop when there is a print statement in the "conditions" of the loop. It seems like an unpractical thing to do (I haven't ever seen it used in any practical way), though my lack of understanding of what is printed has me thinking that I may not fully understand how a for loop functions. The following question showed up on a recent exam:

What will the following method print with an input of n = 5?

public static void mystery(int n) {
    for (int i = -1; i < n; System.out.print(i + " ")) {
         i++;
    }
}

The correct answer is: 0 1 2 3 4 5

To me, it seems that the loop ought to print -1, then increment i by 1, print 0 ..... until i = 4. Then it would print 4, increment i by 1, and break out of the loop at the loop's condition i < n. Why is the correct answer what it is and why is my logic flawed?

解决方案

The initializer expression happens once. Then the condition is checked, then the body of the loop happens, then the increment expression happens (your print statement), and then we start over.

The official tutorial is pretty clear if you read through it.

The Java Language Specification entry for the for statement might also be interesting if you want complete details.

这篇关于for循环如何在Java中检查其条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆