在 for 循环的开头声明有限范围的变量

发布于 2024-08-29 01:03:59 字数 305 浏览 4 评论 0原文

在Java中,有时你会做这样的事情:

for (int a = 1, b = 2; b < high;) {
    if (b % 2 == 0) {
        result += b;
    }

    int tmp = b;
    b       = a + b;
    a       = tmp;
}

这里,我使用for循环而不是while循环来限制a和b的范围。

但我怎样才能在 JavaFX 中实现这一点呢? for循环似乎没有提供这种可能性。我必须使用 while 循环吗?

In Java, you sometimes do something like this:

for (int a = 1, b = 2; b < high;) {
    if (b % 2 == 0) {
        result += b;
    }

    int tmp = b;
    b       = a + b;
    a       = tmp;
}

Here, I used a for loop instead of a while loop to limit the scope of a and b.

But how can I achieve this in JavaFX? The for loop doesn't seem to offer this possibility. Do I have to use a while loop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

或十年 2024-09-05 01:03:59

您可以使用匿名块的 Java 技巧:

var high = 10;

{
    var a = 0;
    for (b in [1..high-1]) {
      // this is fine
      println("{a}");
    }
}
// won't compile here
//println("{a}");

JavaFX 中有类似的表达式,但使用这些表达式您将获得双循环。根据此doc

You could use the Java trick of anonymous blocks:

var high = 10;

{
    var a = 0;
    for (b in [1..high-1]) {
      // this is fine
      println("{a}");
    }
}
// won't compile here
//println("{a}");

The are simmilar expressions in JavaFX but with those expressions you will get a double loop. According to this doc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文