Is the following piece of code redundant? Can I simplify it?
My class just started studying conditional statements in Java using Karel the robot. I was wondering if I could reduce this as I'm becoming suspicious it is unnecessarily repetitive. public void checkdown(){ if(frontIsClear()){ move(); } else{ turnLeft(); if(frontIsClear()){ move(); if(frontIsClear()){ move(); } else{ turnLeft(); } } else{ turnLeft(); } } }
if it turns left on the first try, if it can, it will move twice, perhaps not what you wanted? perhaps you want it to turn left until it can move (but not go in circles so no more than 3 turns) but if it ever can move, do so and return?
This first piece of code does exactly what yours does. public void checkdown(){ if(frontIsClear()){ move(); return; } turnLeft(); if(frontIsClear()){ move(); if(frontIsClear()){ move(); return; } } turnLeft(); } If your goal is to get it moving no matter what... (assuming 90 degree turns), public void checkdown(){ int limit=4; while (!frontIsClear() && limit){ turnLeft(); limit--; } if (limit) // otherwise, robot is surrounded move(); }
is this javascript animation?
You might want to consider making checkdown() control a function: public void foo() { if( frontIsClear() ) move(); else turnLeft(); }
Join our real-time social learning platform and learn together with your friends!