Reputation: 435
Is it possible to skip an if statement and execute another if statement inside that if statement?
if(...){
A code.
}else if(...){
B. Call to C.
}else if(...){
C code.
}else(...){
D code.
}
E.g. if I am in the if statement containing A, and the conditions change so that B is executed, how would I call the code in C WHILST in the B else if statement.
EDIT = Forgot to say that my if statements apart from one returned a custom object array called Dice[]. I have implemented the below solutions and now getting a return statement error.
public Die[] ifA(){
A
}
public void ifB(){
ifC(); ifD();
}
public Die[] ifC(){
C
}
public Die[] ifD(){
D
}
public Die[] roll(){
if(...){ return ifA();
}else if(...){ifC();ifD();
}else if(...){return ifC();
}else(...){return ifD();
}
}
I'm just getting a return error at the end of the roll() method. Surely I shouldn't as I used the else{} block therefore the else WILL have to run if no if/else if statement is executed, no?
EDIT #2 = Just found a workaround for the method that did not return a value. Thanks guys for your input. Made my code a lot neater and understandable!
Upvotes: 2
Views: 31794
Reputation: 911
You could put your A Code
, B Code
, C Code
, and D Code
in their own methods and then call the C Code
while in the B
if statement.
For Example
public void doA() {
//Do what would happen in A
}
public void doB() {
//Do what would happen in B
}
public void doC() {
//Do what would happen in C
}
public void doD() {
//Do what would happen in D
}
and for the if-else-block
if (...) {
doA();
} else if (...) {
doB();
doC();
} else if (...) {
doC();
} else {
doD();
}
Upvotes: 6
Reputation: 2706
Obviously the other two answers are cleaner, but just throwing another way out there.
int condition = 2;
while(true) {
if(condition == 1){
System.out.println(1);
}else if (condition == 2){
System.out.println(2);
condition = 3;
continue;
}else if (condition == 3){
System.out.println(3);
}
break; //if continue gets called it will skip this
}
Upvotes: 0
Reputation: 498
Create a method for the c Code.
if(...){
A code.
}else if(...){
B
cCode();
}else if(...){
cCode();
}else(...){
D code.
}
private void cCode() {
...
}
Upvotes: 4