3
public String toString()
        {
        String str;
        str = "The test scores in descending order are \n";

        for(int i = 0; i < data.length; i++)
        {
            str = str + data[i] + " ";
        }
        str = str + "\nThe average is " + mean;
        return str;
        }

This code for java returns scores in descending order for my code. But what throws me off is the way the 'str' is being returned. How I understand this is the return value of 'str' is (str + "\nThe average is " + mean). Because this is my last updated value of 'str', it will update the 'str' to "The test scores in descending order are" First, Second the loop, then last "str + "\nThe average is " + mean". So in the end even though we updated str a few times the actually printed 'str' will only be "str + "\nThe average is " + mean". Please explain why the program actually ends up printing

The test scores in descending order are 70 80.......... (element values)

(And then returns the average mean value info)

1 Answer 1

4

Because the command was

str = str + "\nThe average is " + mean;

Which means, append to everything already in str and store the results in str. If it was

str = "\nThe average is " + mean;

it would instead replace everything already in str.

Sign up to request clarification or add additional context in comments.

6 Comments

It's easier for new programmers to understand once you grasp the idea that the right side of an assignment is calculated independently of the left side.
Wow, that helps a lot! Thanks so much, once you point that out it's really obvious.
Well there is actually something still unclear, why doesn't the for loop print the "The test scores in descending order are \n" and then the last element of the array? But instead prints all of the array elements. The command str = str + "\nThe average is " + mean; will append everything already in 'str' which seems like it would just be "The test scores...") and then the last element in the for loop?
@WadeAston Because you only added it once. a+b is ab, ab+c is abc (not ababc).
@ElliottFrisch I had to update the last comment it was vague.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.