1

I'm studying for intro comp sci test tomorrow and need to be able to determine the value of different operations. With my calculations t should be equal to 8. But when compiling it returns 11. Why does it run the second if? 2 is not greater than 3. I know it's probably just a misunderstanding problem but it would really help out. Thanks in advance.

public class Prac {     
    public static void main(String []args){
        int i=4, j=3, k=10;
        float r=3, s=2, t=5;
        boolean done = false;

        if (s*2 >= j && t >= s) {
            if (s>j)
                s++;
            t = t * s;
        } else
            t += s;
        t++;
        System.out.println(t);
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
fredo
  • 15
  • 3

1 Answers1

2

The outer condition is true and the inner condition is false.

Therefore the statements executed are:

t = t * s; // 5 * 2 == 10

and

t++; // 11

The code would be clearer with the proper indentation and curly braces:

    if (s*2 >= j && t >= s) { // 2 * 2 >= 3 && 5 >= 2 - true
        if (s>j) { // 2 > 3 - false
            s++; // not executed
        }
        t = t * s; // executed
    } else {
        t += s; // not executed
    }
    t++; // executed
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Good answer, but as long as the indentation is correct (any IDE can do this for you), curly braces don’t make the code more clear IMHO. – Bohemian Nov 15 '18 at 06:02
  • 3
    @Bohemian I guess that's a matter of opinion. I find it painful to the eye when the if clause has curly braces and the else clause doesn't (or vice versa). – Eran Nov 15 '18 at 06:05
  • I understand now, I thought that it had to execute the s++; before the t = t*s;. Thank you for your help. – fredo Nov 15 '18 at 06:08