Reputation:
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.
Upvotes: 0
Views: 102
Reputation: 1316
Let's check this bit of your code:
while (x > 0) {
y = y + 1;
x = x - 1;
}
System.out.println("the solution is " + y);
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 = 0
and y = 36
, the loop stops, because x = 0
and it violates the condition. So you get out of the loop. The last value of y
is 36. That's what you're getting in you println()
; it's not x + y
, it's y
alright.
But when x = -12
, or x=-24
or any other negative number, the while condition is false. Your println()
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()
x
or y
inside the loop, you won't get any result, but won't get any error either.
Upvotes: 0
Reputation: 4896
sum of A and B
when A<0 the sum is not calculated correctly
readout is B when there is error
Upvotes: 0
Reputation: 95958
y
, x
timesA
and B
. In the "worst" case, the loop won't be executed and the initial value of y
will be printedI don't understand your title, there's nothing to do with String[] args
here.
I'm unsure what's the purpose of this code, even for learning purposes..
Upvotes: 2