Android Dev Android Dev - 1 year ago 47
Java Question

Rewriting a conditional chain as a sequence of one-liners

I have this code in Java which controls the main arm of a robot:

if (gamepad1.left_stick_y > 50)
else if (gamepad1.left_stick_y < -50)

That is only a small part, but there are a ton of conditionals just like that, some with only one statement if the condition is true. Can it be simplified to something like: [pseudo-code. Don't take it literally. I know it won't work]

if (gamepad1.left_stick_y > 50) mainArm.setDirection(DIRECTION_FORWARD), mainArm.setPower(50);
else if (gamepad1.left_stick_y < -50) mainArm.setDirection(DIRECTION_REVERSE), mainArm.setPower(50);

Unfortunately, the libraries used for interfacing directly with the hardware for setting power and such are closed source, so modifying them is out of the question.


This code would not compile:

if (gamepad1.left_stick_y>50) mainArm.setDirection(DIRECTION_FORWARD), mainArm.setPower(50);
//                                                                   ^

Your attempt at converting multiple operations into one by placing a comma would not work:

JLS 15.27: Unlike C and C++, the Java programming language has no comma operator.

One approach is to allow changing power and direction in a single call:

if (gamepad1.left_stick_y > 50) mainArm.setDirectionAndPower(DIRECTION_FORWARD, 50);

the libraries for setting power and such are closed source

If you cannot modify the library, you can make your own helper method to address this shortcoming:

private static void setDirectionAndPower(Arm arm, Direction dir, int pow) {