Whenever the button is pressed, I want to set a certain colour. Right now the user can write an int and the corresponding colour is presented (without typing the corresponding int every time). I want to change this though. Every time the user clicks the button, the next colour shall be presented, but I don't know how to rewrite the code. I tried a do while and for loop, but I had problems with the variable used in lambda expression (which apparently should be final)?
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);
});
Right now it looks like this
Change your code that reacts to a button click. That code should:
- Get the currently set color.
- Add one to that color number.
- If that new number exceeds the limit (0-7), then cycle around.
- Set the color to the new color number.
Something like this:
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 ) ;
}
);
I do not see how your lambda would be a problem here. Changing to the code as I showed here does not involve any additional objects outside the scope of the lambda.