์๋ฐ ๋ธ๋ ์ดํฌ
Java์์ Break ๋ฌธ์ ์ฃผ๋ก ๋ค์ ๋ ๊ฐ์ง ๊ฒฝ์ฐ์ ์ฌ์ฉ๋ฉ๋๋ค.- Break๋ ๋ฃจํ๋ฅผ ์ข ๋ฃํ๊ณ ๋ฃจํ ๋ฐ์ผ๋ก ์ ํํฉ๋๋ค(for ๋ฐ while ๋ชจ๋).
- Break ๋ฌธ์ switch ๋ฌธ์์ case๋ฅผ ์ข ๋ฃํฉ๋๋ค.
ํต์ฌ๋ก
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 ๋ฃจํ 0 1์ Test Break ๋ฌธ
์๋ฐ ๊ณ์
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 ๋ฌธ์ ์คํํ ํ์๋ ํ์ฌ ๋ฐ๋ณต์ ๋ํด์๋ง ๋ค์ ์ฝ๋ ์ค์ ๊ฑด๋๋๋๋ค. ๋ฃจํ๊ฐ ๋ค์ ์คํ๋๊ธฐ ์์ํฉ๋๋ค.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