現在、書籍でJavaの学習に取り組んでいます。
この投稿はその備忘録になります。
break文とcontinue文
for文やwhile文を用いた繰り返しの途中で、その繰り返しを中断したいとき、
【break文】
や【for文】
を使います。
■break文
break文を利用した場合
public class App{
public static void main(String[] args) throws Exception{
for (int i = 1; i < 10; i++){
if (i == 3){
break;
}
System.out.print(i);
System.out.print(" ");
}
}
}
【結果】
1 2
以上の様にbreak
によってif文で指定した値以降の処理は中断されています。
(3以降は出力されない)
■continue文
continue文を利用した場合
public class App{
public static void main(String[] args) throws Exception{
for (int i = 1; i < 10; i++){
if (i == 3){
continue;
}
System.out.print(i);
System.out.print(" ");
}
}
}
【結果】
1 2 4 5 6 7 8 9
以上の様にcontinue
によってif文で指定した値の処理は中断されています。
(3のみ出力されない)
以上になります。