0

Having troubles understanding the short hand thing, for example x+=y is the same as x=x+y, how can x=x and x=x+y

is this how the lesson was ment to be explained or was a mistake made? am i looking at it wrong? because if i put say: x=5 then on a lower line put x=4 that will throw an error.

25th Jan 2020, 5:14 PM
Dillon Flannery
Dillon Flannery - avatar
7 Answers
25th Jan 2020, 5:24 PM
BroFar
BroFar - avatar
25th Jan 2020, 8:37 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
I am not familiar with ruby but x += y also exists in java. for example x = 4. means x has the value 4. x += 5 means x gets the value of itself + 5. x = 4 + 5 = 9
25th Jan 2020, 5:21 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
About the error: I tried this: x = 5 x = 4 print(x) Works. Output: 4
25th Jan 2020, 5:23 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
ok one more question, so after you do the x+=y or what ever, x is storing that new value after that correct?
25th Jan 2020, 5:26 PM
Dillon Flannery
Dillon Flannery - avatar
+ 1
In Java it works like this: int x=1; //now x stores 1 int y=2; //now y stores 2 x+=y; /*now y stays 2, but we have to add the value of y to x(which is 1 before the operation. And make x store the new value. So, 1+2 = 3 and now x=3; y =2*/
27th Jan 2020, 3:26 PM
Anna
+ 1
[In Java] Yes, x stores the new value after these operaions: = += -= /= %= Don't mix up == and =. The first one is checking if the numbers are the same. The other is assigning. For example, if (x==y) { /*comparing without assigning new values*/ System.out.println ("x and y are the same numbers"); } x=y; /*assigning value of y to x. Now they both have the same value*/
27th Jan 2020, 3:34 PM
Anna