user4281951
user4281951

Reputation:

Java, Understanding

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);
}
  1. 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.

  2. 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?

  3. 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

Answers (3)

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:

  • x = 11, y = 25
  • x = 10, y = 26
  • x = 9, y = 27
  • x = 8, y = 28
  • x = 7, y = 29
  • x = 6, y = 30
  • x = 5, y = 31
  • x = 4, y = 32
  • x = 3, y = 33
  • x = 2, y = 34
  • x = 1, y = 35
  • x = 0, y = 36

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

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

  1. sum of A and B

  2. when A<0 the sum is not calculated correctly

  3. readout is B when there is error

Upvotes: 0

Maroun
Maroun

Reputation: 95958

  1. Incrementing y, x times
  2. There'll be no errors for any A and B. In the "worst" case, the loop won't be executed and the initial value of y will be printed
  3. Irrelevant

I 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

Related Questions