ジャバブレイク
Javaにおけるbreak文は主に以下の2つのケースで使用されます。- Break はループを終了し、そこから飛び出します (for と while の両方)。
- Break ステートメントは switch ステートメント内のケースを終了します。
構文
break;
例
public class Driver1 {
public static void main(String[] args) {
// Testing break statement in while loop
System.out.println("Test Break statement in While loop");
int i = 0;
while (i < 5) {
if (i == 2) {
break;
}
System.out.println(i++);
}
}
}
出力
While ループで Break ステートメントをテストする 0 1
Java 続行
Java の continue ステートメントは、次のような場合によく使用されます。- 次のステートメントをスキップし、forループ内の次の反復に移動します。
- while ループを続行すると、次のステートメントをホップし、条件ステートメントにジャンプします。
構文
continue;
例
public class Driver2 {
public static void main(String[] args) {
// Testing continue statement in while loop
System.out.println("Test Continue in While loop");
int i = 0;
while (i < 5) {
if (i == 2) {
i++;
continue;
}
System.out.println(i++);
}
}
}
出力
While ループでテストを続行 0 1 3 4
継続と中断の違い
Break と continue の大きな違いは、break はループをすぐに終了することです。Break ステートメントが実行されると、ループは再度実行されません。ただし、 continue ステートメントの実行後は、現在の反復でのみ次のコード行がスキップされます。ループが再び実行され始めます。While ループでの中断と続行
Break と Continue は両方ともwhileループで使用できます。明確に理解するために、以下の例を見てみましょう。例
public class Driver {
public static void main(String[] args) {
// Testing both break and continue statements side by side
String [] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
System.out.println("Test Break statement in While loop");
System.out.println("\nWorking Days:\n");
int i = 0;
while (i < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
i++;
break;
// Not any working day will be printed
// because the loop breaks on Sunday
// once the loop breaks it moves out of the loop
}
System.out.println(weekdays[i++]);
}
System.out.println("\nTest Continue statement in While loop");
System.out.println("\nWorking Days:\n");
int j = 0;
while (j < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
j++;
continue;
// All the working/business days will be printed
// when the loop encounters Saturday or Sunday
// it skips that iteration and continues to the next iteration
}
System.out.println(weekdays[i++]);
}
// A test case for continue statement using for loop
System.out.println("\nTest Continue in For loop");
for (int x = 0; x < 5; x++) {
if (x == 2)
continue;
System.out.println(x);
}
}
}
出力
While ループの Break ステートメントのテスト 営業日: While ループのテスト Continue ステートメント 営業日: 月曜日、火曜日、水曜日、木曜日、金曜日 For ループのテスト続行 0 1 3 4
GO TO FULL VERSION