In Challenge 11, entering the code as−is creates an error message, saying that the method goFigure cannot be referenced from a static context. When the term “static” is removed from the “output” code−segment, then one cannot run the program. To combat this problem, one can add the word “static” in front of the coding “double goFigure(int n)”. When this is done, the output is “2.0 12”. At first, the challenge assigns n as an integer equal to 12. The method goFigure then has n perform the function “n % 7”, which means “the remainder of ‘n ÷ 7’ ”. This number is 5, and is then used in the next statement “12 / n”. Because n is assigned an “int” value, the answer is rounded to 2. After that, n is reassigned as a “double” value, making goFigure(n) equal 2.0. In the last bit of code, the value of goFigure(n), or 2.0, is printed on the screen, followed by a space and the original value of n, being 12; thus, when run, the output is “2.0 12”.
−Phoenix
Phoenix, you've done very well here, not only catching my mistake, bit also in explaining the behavior. I have one item of follow-up here:
ReplyDeleteBy the time we get to this line in the sequence of this program:
n = n % 7;
How many variables do we have in computer memory named n?
When the line “n = n % 7” is reached, there are two variables named “n”. They are “n”, (being an “int” value of 12), and “goFigure(n)”, (being an “int” value of 5).
ReplyDelete−Phoenix
Most excellent, this touches on the idea of something we call "scope", and we will be spending some time with that concept. Well done. 15 XPs for this completion.
ReplyDelete