Online Course Discussion Forum

AP CSA Break/For/WHile loop return

 
 
zselina的头像
AP CSA Break/For/WHile loop return
zselina - 2022年08月15日 Monday 13:36
 

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!

 
zselina的头像
Re: AP CSA Break/For/WHile loop return
zselina - 2022年08月15日 Monday 14:12
 

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])?

WangDr. Kevin的头像
Re: AP CSA Break/For/WHile loop return
WangDr. Kevin - 2022年08月16日 Tuesday 00:16
 

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.