I have the following questions, about this Java Code:
public static void main(String[] args) {
int A = 12, B = 24;
int x = A, y = B;
while (x > 0) {
y = y + 1;
x = x - 1;
}
System.out.println("the solution is " + y);
}
What is beeing computed here? My solution is, that it's (12-1)+(24+1) = 36. Please correct me if it's the wrong though.
For which A and B there will be an error? Honestly, i though about A = 1 and smaller, but it didn't work....can someone help me out?
If there's an error, what is the readout? I could not answer this, as trying out to get an error (for example setting A = -24) i just did not get an error but another solution.
Let's check this bit of your code:
This is a loop. A while loop, to be precise.
A loop will continue to iterate until the condition of the loop is false
In this case, you have x = 12 and y = 24. Since x value is positive, so it will enter the loop, and continue the calculation for each iterations.
Here are the results you'll get for each iteration:
When you get
x = 0andy = 36, the loop stops, becausex = 0and it violates the condition. So you get out of the loop. The last value ofyis 36. That's what you're getting in youprintln(); it's notx + y, it'syalright.But when
x = -12, orx=-24or any other negative number, the while condition is false. Yourprintln()is outside the loop, so it will display the value of y which is outside the loop, i.e. 24.You won't get an error for condition of while being false. Even if you
println()xoryinside the loop, you won't get any result, but won't get any error either.