每当按下按钮时,我想设置某种颜色。现在用户可以写一个 int 并显示相应的颜色(无需每次都键入相应的 int)。 不过我想改变这一点。每次用户单击按钮时,都会显示下一种颜色,但我不知道如何重写代码。 我尝试了 do while 和 for 循环,但我在 lambda 中使用的变量有问题表达式(显然应该是最终的)?
board.setButton2Text("Select");
board.setButton2Action(() -> {
int c = 0;
while(!(c > 0 && c < 7)) {
try {
c = IO.inputInt("Type an int ranging from 1 to 6");
} catch (RuntimeException e) {
continue;
}
}
currentCode.setColor(selectedCircle, c);
drawCode(X_START, Y_START + LINE_SPACING * (6 - currentTry), currentCode);
});
现在看起来像这样
最佳答案
更改对按钮点击使用react的代码。该代码应该:
- 获取当前设置的颜色。
- 给该颜色编号加一。
- 如果新数字超过限制 (0-7),则循环。
- 将颜色设置为新的色号。
像这样:
board.setButton2Action( () -> {
// On each click of the button, rotate to the next color in a sequence of colors numbered 0-7.
int c = currentCode.getColor( … ) ; // TODO: Add assertion tests to verify you get back a valid value as expected.
c = ( c + 1 ) ; // Increment the color.
if( c == 8 ) { // If past the limit…
c = 0 ; // …go back to first number.
}
currentCode.setColor( selectedCircle , c ) ;
drawCode( X_START , Y_START + LINE_SPACING * ( 6 - currentTry ) , currentCode ) ;
}
);
我不认为您的 lambda 在这里会是个问题。更改为我在此处显示的代码不会涉及 lambda 范围之外的任何其他对象。
关于java - 每次按下按钮时呈现颜色(lambda 表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176806/