Reputation: 153
Suppose I had 2 for loops, each contains an if and else statement, I want it to work so that if the first for
loop is achieved then to break and not run the second for loop. Probably a very simple solution, thanks any help.
The aim of this program is to read a user input and iterate over the int
given, if the user doesn't input a int value then to iterate over 100.
As this code is everything is working except it is doing both loops, I want it to do one or the other.
package coreprog;
...
for (...){
...
if (...) {
...
}
else
System.out.println(...);
}
for (...){
...
if (...) {
...
}
else
System.out.println(...);
Upvotes: 1
Views: 63
Reputation: 34424
Keep a Boolean flag inside first for loop and Make it true before break.Based on it do it whatever you want to do. For example :-
boolean firstConditionAchieved= false;
for (...){
...
if (...) {
firstConditionAchieved = true;
...
}
else
System.out.println(...);
}
Second loop :-
if(!firstConditionAchieved){
......
}
Upvotes: 2
Reputation: 4184
If you want to read an int
value and iterate over it, or over 100 if not supplied, you only need one loop.
read N
if not read or not valid N then N = 100
for i = 1 to N do
...
Upvotes: 0
Reputation: 4411
Make use of boolean variable and check the boolean variable in if condition. If the variable is set skips out of the loop and doesn't execute the second loop and do the vice versa.
Upvotes: 0