Combine if statements

150 Views Asked by At

So i have these if statements and I have 2 questions. First is there a way to combine these statement to make 1 big if condition. Also, I was wondering if there was a way to make it so if the condition is true then automatically end the method. I don't actually want to say "no freight train" I want to end the method if the if statement are true.

public void rule4(ArrayList<Integer> dierolled){
    if (dierolled.contains(1)){
        System.out.println("no freight train");
    }
    if (dierolled.contains(3)){
        System.out.println("no freight train");
    }
    if (dierolled.contains(10)){
        System.out.println("no freight train");
    }

}

5

There are 5 best solutions below

2
Luke C On BEST ANSWER

To combine if statements, try this:

if (dierolled.contains(1) || dierolled.contains(3) || dierolled.contains(10)) {
    System.out.println("no freight train");
}

The above is essentially saying this: If dierolled contains 1 OR dierolled contains 3 OR dierolled contains 10 then print "no freight train"

if (dierolled.contains(1) && dierolled.contains(3) && dierolled.contains(10)) {
        System.out.println("no freight train");
    }

The above is essentially saying this: If dierolled contains 1 AND dierolled contains 3 AND dierolled contains 10 then print "no freight train"

To end the method, simply add return;

0
Bentaye On
public void rule4(ArrayList<Integer> dierolled){
    if (dierolled.contains(1) || dierolled.contains(3) || dierolled.contains(10)) 
    return;
}

or return the boolean value if you need to use it somewhere:

public boolean rule4(ArrayList<Integer> dierolled){
    return dierolled.contains(1) || dierolled.contains(3) || dierolled.contains(10) 
}
0
cнŝdk On

You just need to use one if statement with the 3 conditions and a return statement at the end to quit the method:

public void rule4(ArrayList<Integer> dierolled){
    if (dierolled.contains(1) || dierolled.contains(3) || dierolled.contains(10)){
        System.out.println("no freight train");
        return;
    }

}
3
Elliott Frisch On

Assuming you are using Java 8+, you could use the element stream() from your dierolled List and check if any terms match. If so, return; - otherwise do what you want to do when there is "a freight train". Like,

public void rule4(ArrayList<Integer> dierolled) {
    if (dierolled.stream().anyMatch(x -> x == 1 || x == 3 || x == 10)) {
        return;
    }
    System.out.println("freight train");
}
0
Zach Ford On
public void rule4(ArrayList<Integer> dierolled){
    if (dierolled.contains(1) 
            || dierolled.contains(3)
            || dierolled.contains(10)
       )
    {
        return;
    }
    /* Other code can go here */
 }

Should work. You might also want to factor out the 'IF' conditions into their own method for readability, such as private boolean noFreightTrain(List<Integer> dieRolled)