There is no guarantee that your for loop will be entered e.g. if degree is -2
If the loop is skipped there is no return statement after loop to return a String. Since your toString() method has to return a String, the compiler complains about it. I would suggest adding a return statement after your loop to return a default value if the degree is invalid i.e. return null or "".
It doesn't really make sense to set up a loop that will always return on the first iteration. You need to think through what you are intending to do. If you are going to have a loop, then you need a return statement after the loop, just in case you never enter the loop body.
As others have already indicated, what you can do, I'll tell you where it is wrong. in your code, even if you enter your for loop, there are chances that if condition was never met, what will happen then?
It is better practice to have one return statement unless until you want to make your code more efficient in some particular situations, Like in a method if execution falls through varied conditions all with if statement, then you will likely to exit as sson as you met one of those. In if..else style, anyway you will exit, if one of hem is met.
posted 9 years ago
Thanks for the help.
Ok, what I am trying to do is to loop through the array and concatinate the results into a string as a decrements.
Maybe the best way would be to assign it to a variable and return that variable after the loop? Is that the right thinking?
Thanks for all your help!
posted 9 years ago
ok, so you can see from my above code that the return is wrong. I understand the clarifications by everyone on how the return shouldn't be in the for loop. To fix that I was thinking to create some sort of variable and as it loops through the forloop/array it concatinates the strings to a result that I can return at the end, outside of the forloop.
My result I am trying to achieve is this ; assertEquals("4x^3 + 3x^2 + 2x^1 + 1x^0", p1.toString());
I'm not sure what Rahul means about two returns making things more efficient in certain situations. You do need to understand how return affects the flow of your method and decide if that makes sense with your goals. Talk through a scenario if that helps you understand what's going on. For example, if degree is 2, then i will be set to 3. 3 >= 0 is true so we will enter the loop. We will take coefficient and see if it is 0. It's 4, so we run the else instructions to build the string "4x^3" and return it to the caller, effectively ending the loop. As you pointed out, that's not what you wanted.
I think you're on to something with keeping a variable, continually concatenating to it, then returning it after the loop is done. Talk through that idea, or work it out on paper, and once you have your thoughts straight, put it into code.
He's my best friend. Not yours. Mine. You can have this tiny ad: