This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I'll give a general description of the issue I am faced with:
I have a for... loop, inside which there is an if... statement. Now, the else part of this if statement cannot be nested within the for...loop (because I don't want the else... part to loop). Outside the for...loop, there is a statement I want to execute, but it should not execute if what is contained within the if...statement inside the for loop executes (it is basically the else..part of the if...statement within the for...loop, but I cannot put it inside the for...loop because I want it to execute only once).
How do I control the flow of my program to achieve this?
Basically, I want to do a GOTO like implementation (I know how to do this with GOTO). How do I implement it in Java/JSP?
Thanks a ton. [ January 16, 2008: Message edited by: Bear Bibeault ]
How do you implement it in Java with "goto?" Easy: you don't.
It is a little difficult to understand what you want, but the notion of an "if" inside a loop and an "else" outside a loop seems to be impossible to implement.
The idea of structured processing is to get rid of "goto" and its surrogates, which include "break" "continue" and multiple "return." That is why the JavaRanch code style (here-see 3.1) tells us not to use them.
Suggest you try this sort of thing:
declare a boolean local variable and initialise it to "false".
Apply some test in the loop and then apply its value to this variable. That can be inside or outside the "if."
After the loop, set up another if with !myBoolean as its condition.
That is what I would try. Other people might try something different
So - you're running through the loop, doing your 'if' test each time. If, at any time, you enter the 'if' section of code (your condition is true), you set the 'doneIf' flag, to say so. Then, once you've finished the loop, you look at the flag, to see whether your condition ever evaluated to true. If not, you do your 'else' code.
[EDIT: Sorry, posted at the same time as Campbell, I think we agree though ] [ January 16, 2008: Message edited by: David Payne ]