Java: Can you explain me the output?
7 minutes ago, Hip said:I coded it with a Nassi Schneidermann Diagram I got from university. And the code is 1:1 like the solution by the prof.
I was expecting the output to be "2". Because when I put in "9" and "7" the first if loop calculates 9 - 7 = a. Shouldn't a be "2" then? But it still goes into the second if loop where b == 0, but why is b == 0 here? I thought it's "7" because I input it before to be "7". This is the part I don't understand.
Well yes, the first time it goes through the loop a becomes 2. But now a is 2 and b is 7. Both are bigger than 0 so the loop executes a second time. Here is your loop condition:
while(a > 0 && b > 0)
Now b is bigger than a so the else block gets executed which calculates b = b - a; which makes b equal 5. But a = 2 and b = 5 so the loop gets executed another time, now a = 2 and b = 3 . Now it gets executed another time a = 2 b = 1. Now a is bigger than b so a = a - b; which means now a = 1 and then b = 1 and both are still bigger than 0 so we execute the code in the while block another time which calculates b = b - a; which leads to a = 1 and b = 0. Now b is NOT bigger than 0 so the while loop ends and we go to the following if statement:
if(b == 0) { JOptionPane.showMessageDialog(null, "a : " + a); } else { JOptionPane.showMessageDialog(null, "b: " + b); }
because b == 0 the message dialog shows you the value of a, which is 1.
I think you might be forgetting about the while loop, and that's what's confusing you.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now