Movatterモバイル変換


[0]ホーム

URL:


Documentation

The Java™ Tutorials
Language Basics
Variables
Primitive Data Types
Arrays
Summary of Variables
Questions and Exercises
Operators
Assignment, Arithmetic, and Unary Operators
Equality, Relational, and Conditional Operators
Bitwise and Bit Shift Operators
Summary of Operators
Questions and Exercises
Expressions, Statements, and Blocks
Questions and Exercises
Control Flow Statements
The if-then and if-then-else Statements
The switch Statement
The while and do-while Statements
The for Statement
Branching Statements
Summary of Control Flow Statements
Questions and Exercises
Trail: Learning the Java Language
Lesson: Language Basics
Section: Control Flow Statements
Home Page >Learning the Java Language >Language Basics
« Previous • Trail • Next »

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Branching Statements

Thebreak Statement

Thebreak statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of theswitch statement. You can also use an unlabeledbreak to terminate afor,while, ordo-while loop, as shown in the followingBreakDemo program:

class BreakDemo {    public static void main(String[] args) {        int[] arrayOfInts =             { 32, 87, 3, 589,              12, 1076, 2000,              8, 622, 127 };        int searchfor = 12;        int i;        boolean foundIt = false;        for (i = 0; i < arrayOfInts.length; i++) {            if (arrayOfInts[i] == searchfor) {                foundIt = true;break;            }        }        if (foundIt) {            System.out.println("Found " + searchfor + " at index " + i);        } else {            System.out.println(searchfor + " not in the array");        }    }}

This program searches for the number 12 in an array. Thebreak statement, shown in boldface, terminates thefor loop when that value is found. Control flow then transfers to the statement after thefor loop. This program's output is:

Found 12 at index 4

An unlabeledbreak statement terminates the innermostswitch,for,while, ordo-while statement, but a labeledbreak terminates an outer statement. The following program,BreakWithLabelDemo, is similar to the previous program, but uses nestedfor loops to search for a value in a two-dimensional array. When the value is found, a labeledbreak terminates the outerfor loop (labeled "search"):

class BreakWithLabelDemo {    public static void main(String[] args) {        int[][] arrayOfInts = {             { 32, 87, 3, 589 },            { 12, 1076, 2000, 8 },            { 622, 127, 77, 955 }        };        int searchfor = 12;        int i;        int j = 0;        boolean foundIt = false;    search:        for (i = 0; i < arrayOfInts.length; i++) {            for (j = 0; j < arrayOfInts[i].length;                 j++) {                if (arrayOfInts[i][j] == searchfor) {                    foundIt = true;                    break search;                }            }        }        if (foundIt) {            System.out.println("Found " + searchfor + " at " + i + ", " + j);        } else {            System.out.println(searchfor + " not in the array");        }    }}

This is the output of the program.

Found 12 at 1, 0

Thebreak statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.

Thecontinue Statement

Thecontinue statement skips the current iteration of afor,while , ordo-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates theboolean expression that controls the loop. The following program,ContinueDemo , steps through aString, counting the occurrences of the letter "p". If the current character is not a p, thecontinue statement skips the rest of the loop and proceeds to the next character. If itis a "p", the program increments the letter count.

class ContinueDemo {    public static void main(String[] args) {        String searchMe = "peter piper picked a " + "peck of pickled peppers";        int max = searchMe.length();        int numPs = 0;        for (int i = 0; i < max; i++) {            // interested only in p's            if (searchMe.charAt(i) != 'p')                continue;            // process p's            numPs++;        }        System.out.println("Found " + numPs + " p's in the string.");    }}

Here is the output of this program:

Found 9 p's in the string.

To see this effect more clearly, try removing thecontinue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.

A labeledcontinue statement skips the current iteration of an outer loop marked with the given label. The following example program,ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program,ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop.

class ContinueWithLabelDemo {    public static void main(String[] args) {        String searchMe = "Look for a substring in me";        String substring = "sub";        boolean foundIt = false;        int max = searchMe.length() -                   substring.length();    test:        for (int i = 0; i <= max; i++) {            int n = substring.length();            int j = i;            int k = 0;            while (n-- != 0) {                if (searchMe.charAt(j++) != substring.charAt(k++)) {                    continue test;                }            }            foundIt = true;                break test;        }        System.out.println(foundIt ? "Found it" : "Didn't find it");    }}

Here is the output from this program.

Found it

Thereturn Statement

The last of the branching statements is thereturn statement. Thereturn statement exits from the current method, and control flow returns to where the method was invoked. Thereturn statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after thereturn keyword.

return ++count;

The data type of the returned value must match the type of the method's declared return value. When a method is declaredvoid, use the form ofreturn that doesn't return a value.

return;

TheClasses and Objects lesson will cover everything you need to know about writing methods.

« PreviousTrailNext »

About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights

Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.

Previous page: The for Statement
Next page: Summary of Control Flow Statements

[8]ページ先頭

©2009-2025 Movatter.jp