gpt4 book ai didi

java - 是否可以编写逻辑形式 "then if"的条件?

转载 作者:行者123 更新时间:2023-12-02 01:05:23 24 4
gpt4 key购买 nike

我目前正在尝试自学在Processing 3 中编写代码。查看引用文档后,没有 then if (*expression*) {} 语句。我最好的猜测是,我需要将 if (*expression*) {}else if (*expression) 语句串在一起,但到目前为止我还无法获得类似于直接 then if 语句的内容。我该如何去做这样的事情?

根据评论,我发现我应该提供一个示例案例。我什至不完全理解逻辑,所以这可能很困惑,但这是我最好的尝试:

假设我想在控制台上绘制一个正方形,其中有 int x = 0int y = 0rect(x, y, 20, 20)。然后我想按顺序绘制多个正方形并跟踪正方形的数量。然后,如果方 block 的数量等于十,我想用随机确定的颜色填充每个方 block 。每十个方 block 都用作触发器,告诉程序改变每组十个方 block 的颜色。

我应该补充一点,尽管可能有一种更简单的编写方法,可能涉及像 forwhile 这样的循环语句,但我正在尝试挑战自己使用我已经学到的东西来写这个。

我当前的代码如下所示;请记住,这绝不是完整的,并且可能存在其他错误,因为我刚刚开始学习编码,而且还不够完美:

    1. //global variables:
2. int x = 0;
3. int y = 0;
4. int numberOfSquares = 0;
5.
6. void setup() {
7.
8. // note that the size of the window is
9. // currently needlessly large, but this
10. // is the intended final size for the
11. // end result of this exercise
12. size(1000, 1000);
13. frameRate(5);
14. }
15.
16. void draw() {
17. //local variables: none yet
18.
19. // if statement used to draw ten squares
20.
21. if (numberOfSquares < 10) {
22. rect(x, y, 20, 20);
23. x = x + 40;
24. y = y + 40;
25. numberOfSquares = numberOfSquares + 1;
26.
27. // then, if ten squares exist, and only then
28. // fill each square with a random color
29.
30. if (numberOfSquares == 10) {
31. fill (random(255), random(255), random(255));
32. }
33. }
34. }
35.
36. // from here, draw 10 squares again,
37. // maintaining the original fill until
38. // another 10 squares are drawn

此编辑中可能还存在一些格式错误;这是我第一次使用堆栈页面,所以我还不完全熟悉这些约定。我很抱歉。

最佳答案

我不清楚你的意思,但这里有一些例子可以澄清问题。五月...

if (expression) {
// If expression is true, then do this.
else if (anotherExpression) {
// If expression is false, check whether anotherExpression is true.
// If it is, do this.
// There can be more than one "else if" chained one after the other.
} else {
// If all those "if" and "else if" expressions were false, then do this.
// The "else" part of an "if" is not required.
}

官方 Java 教程有一个很好的页面介绍了不同类型的 if 语句: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html

现在,如果您想链接条件:

if (expression && anotherExpression) {
// Do this if both expressions are true.
}

if (expression) {
// Do something if expression is true.
if (anotherExpression) {
// Do this if anotherExpression is also true.
// Since this block is inside the first "if", it needs both
// expression and anotherExpression to be true.
}
}

当然,您可以混合搭配这些。

关于java - 是否可以编写逻辑形式 "then if"的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60117436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com