Jumping around - break, continue, return
Code is usually executed linearly or in loops. However, sometimes you may want the program to jump to a different spot of code. This could create very confusing code if unrestricted, so Java limits jumping to special cases.
break
The previous node mentioned how the break
keyword is used to exit from a switch
statement. It can also be used to exit from any loop (for, while and do-while). When used in a loop, the program will break out of the loop and continue executing code from after the loop block. Here's a simple example:
for(int i=0; i<100; i=i+1) {
if(i == 7){
break;
}
System.out.println(i);
}
System.out.println("finished");
This code will output the following:
0 1 2 3 4 5 6 finished
When i
equals 7, the program breaks out of the loop, so no further numbers get printed. This code is a simple demonstration of break
, but would not make sense to use in practice, since the condition of the loop can just be changed to i<7
instead of i<100
. break
should instead be used when there's a special circumstance not covered by the main condition of a loop. For example, it could be used to find the position of a number in an array:
public static void findNum(int[] array, int num)
{
int i;
boolean isThere = false;
for (i = 0; i < array.length; i=i+1) {
if (array[i] == num) {
isThere = true;
break;
}
}
if (isThere) {
System.out.println(num + " is at index " + i);
} else {
System.out.println(num + " isn't in array");
}
}
The above code goes through array
and stops when it reaches num
. It then prints out the location of num
.
The following code calls the above method to find 30
in an array:
int[] ar = {0,10,20,30,40};
findNum(ar, 30);
It will output:
30 is at index 3
If it passed in a number not in the array:
findNum(ar, 50);
it will output:
50 isn't in array
As long as num
hasn't been found, the loop needs to finish searching through array
. However, one the number is found, there's no reason to continue searching, so it makes sense to use break
.
labels and nested loops
When break
is used in nested loops, it will exit from the innermost loop. In some cases, you may wish to jump to the outside of an outer loop.
Java allows you to specify which loop to break out of with labels:
break labelName;
This will jump to the right after the block of code marked with labelName
. To mark a block of code with a label, simply state the labelName before the block of code:
labelName:
for(int i=0; i<100; i=i+1) {
//body of loop...
}
In the following code a double-array is searched:
public static void findNestedNum(int[][] board, int num)
{
int i;
int j = 0;
boolean isThere = false;
outer:
for (i = 0; i < board.length; i++) {
for (j = 0; j < board[i].length; j++) {
if (board[i][j] == num) {
isThere = true;
break outer;
}
}
System.out.println(num + " not in row " + i);
}
if (isThere) {
System.out.println(num + " is at row " + i + ", cell " + j);
} else {
System.out.println(num + " not in the array");
}
}
public static void testNest()
{
int[][] board = {
{ 0, 2, 4, 6 },
{ 10, 120, 144, 166 },
{ 2000, 2002, 2040, 2600 }
};
findNestedNum(board, 4);
findNestedNum(board, 1);
findNestedNum(board, 2600);
}
Calling testNest will product the following output:
4 is at row 0, cell 2 1 not in row 0 1 not in row 1 1 not in row 2 1 not in the array 2600 not in row 0 2600 not in row 1
The label outer
marks the outer loop. When a number is found, the statement break outer;
will exit both loops, so the "not in row" statement will be skipped and the code will continue below.
continue
On rare occasion, you may want to skip the current iteration through a loop without exiting the loop entirely. You can use continue
to do this. Here's a simple example for printing numbers from 0 through 6, except 3:
for(int i=0; i<7; i=i+1) {
if(i == 3){
continue;
}
System.out.println(i);
}
System.out.println("finished");
This will output:
0 1 2 4 5 6 finished
When i
was 3, the code reached continue
, but it did not exit the loop like by break
. Instead, it just skipped the remaining code in the current iteration of the loop (the print statement), and continued at the top of the loop with i
as 4.
return
While break
and continue
aren't used that often, return
is a fundamental part of programming. Methods that declare a return type need to always return a value of that type. When return is called, the program returns to the code that originally called the method.
public class Sample
{
public static void main(String[] args)
{
int n2 = doubleNum(5);
System.out.println(n2);
}
public static int doubleNum(int num){
return num * 2;
}
}
When the main method runs in the above code:
- doubleNum is called and passed a
5
. - doubleNum returns
10
- The program returns to
main
and assigns10
ton2
- The main method continues by printing out
10
and the program finishes running.
void return
Methods with a void
return type will usually run through their whole block of code and then the program will return to the previous code. However, on occasion you may want to return
nothing to end execution of the method and return immediately to the previous code. The above method findNum
could be refactored to use return
instead of break
:
public static void findNum2(int[] array, int num)
{
for (int i = 0; i < array.length; i++ ) {
if (array[i] == num) {
System.out.println(num + " is at index " + i);
return;
}
}
System.out.println(num + " not in array");
}
This method does the same thing as before, but with less code.
Challenge
In the game of OddCards, only the odd-valued cards count. Each hand of cards is worth the sum of the odd-valued cards. However, multiples of 3 are deadly! If you get a card that is odd and is a multiple of 3 you lose all your points and the hand is scored at 0.
You will be given an array cards
that contains the integer values of a hand of cards. Write a method that returns the score of cards
.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Shane
Nov 3, 7:52 AMThe example doesn't work. Input 2 gives a sum of 22, so shouldn't go back to 0, input 4 sums to 4 and again shouldn't be zero'd.
Learneroo
Nov 3, 11:23 PM@Shane, those hands contain odd multiples of 3, which cause the score to be 0. I added some explanation above.
Mandy
Oct 27, 5:29 AMHow do I resolve this?
for (int i=1; i<cards.length; i++) {
if (i%2!==0 && i%3!==0) {
System.out.println(sum +=i);
}
}
}
Mandy
Oct 27, 12:11 PMis there any hint? I'm stuck :(
Mandy
Oct 27, 12:11 PMstatic int doStuff(int[] cards){
for (int i=1; i<cards.length; i++) {
if (i%3==0) {
break;}
if (i%2!==0 && i%3!==0) {
System.out.println(sum +=i);
}
System.out.println("0")
Cliff Karlsson
Jan 29, 3:54 AMWhen you get a multiple of 3 remember that the whole hand gets to 0 no matter the cards before or after. Use break in that case.
thales
Jul 9, 2:23 PMWhy are there no awnsers anywere?
thales
Jul 9, 2:57 PMHere is the awnser i forgot sum=0; before the break. devil in the details i guess.
my code
catypus
Dec 19, 7:38 AMOK I'm lost here...
I think, according to the instructions my code is right. See the expected output. I think theres a mistake!
Input Correct Output Your Output
1 2 6 7 8 0
1 2 4 5 7 9 0 0
2 4 8 11 13 24 24
1 2 3 4 0 0
1 2 6 7 should return 0 because 6%3==0!! Why are you saying it should equal 8???
My code:
int score=0;
catypus
Dec 19, 7:38 AMOK never mind LOOOOLL