Online Course Discussion Forum

AP CSA Break/For/WHile loop return

 
 
Picture of selina z
AP CSA Break/For/WHile loop return
by selina z - Monday, August 15, 2022, 1:36 PM
 

Hello,

While working on #2 on 2014 AP csa FRQ, I was wondering whether it's legal to use a return statement in a for or while loop without using a break; cmd afterwards. Besides using an else, how to specify the other return?

Ex.


for(int k = 0; k< arr.length; k++){

     if arr[k] = 8; return true;

}


return false; //Is this command disregarded if the return true; from above comes into play?

An alternative I have to this issue is using a variable within the method, such as isTrue = (someDefault) or result = 3; changing this variable's value in some cases of the for/while and then regardlessly returning "result". However, does this get considered "excessive use of data?" ie is there a way to avoid creaeting this extra variable?


Thank you!

 
Picture of selina z
Re: AP CSA Break/For/WHile loop return
by selina z - Monday, August 15, 2022, 2:12 PM
 

Also when calling on private variables of the object in question (ex this.privateArray[k]) must I use a method to call on this private field information first or can I directly call as is (examples: this.privateVariable, this.privateArray[row][col])?

Picture of Dr. Kevin Wang
Re: AP CSA Break/For/WHile loop return
by Dr. Kevin Wang - Tuesday, August 16, 2022, 12:16 AM
 

Selina, did you put the code into an actual Java file and run it?  It is the sure way to test what you are asking.  Please get into the habit of testing with the real programming, instead of just looking at the code.

Having "return" inside a loop is perfectly okay.  In fact it was discussed in one of our lectures.  Look at the slides of the corresponding lesson.  The way you described above is good in terms of the algorithm, but the syntax of what you wrote is not correct Java syntax.

Also, if you use an extra variable to indicate whether it is time to get out of the loop and return, it is perfectly fine too.  There is no such thing as "excessive use of data" error.  The AP reader will also grade it as correct, given that you don't have error elsewhere.