while 반복문

Dec 16, 2023
while 반복문
 
💡
while(조건) 에서 조건이 참일 때 반복 실행 정해진 조건이 없다면 무한 반복
 
public static void main(String[] args) { int i = 0; while (i < 10) { System.out.println("Hello"); i = i + 1; }
 
변수 i = 0의 값으로 시작할 때 반복문에서 i 가 10보다 작으면 반복문이 실행된다.
notion image
 
반복문이 실행될 때 마다 i 값이 1씩 증가한다. 이 조건이 없다면 i 는 0 으로 고정되어 있기 때문에 Hello 가 무한 반복된다.
 
 
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { //true를 넣으면 반복문이 무한반복 System.out.print("정수를 입력하시오 :"); int number = sc.nextInt(); if (number > 0) { System.out.println("양수입니다."); } else if (number < 0) { System.out.println("음수입니다."); } else { System.out.println("0입니다."); } }
 
while 값에 true 를 입력하면 항상 참이기 때문에 반복문이 무한히 반복된다.
notion image
 
💡
break문 : 반복문을 벗어날 때 사용 countiue문 : 현재의 반복을 건너뛰어 다음 반복으로 넘어감
 
 
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { //true를 넣으면 반복문이 무한반복 System.out.print("정수를 입력하시오 :"); int number = sc.nextInt(); if (number == 198) { break; //반복문을 나올 때 조건 } if (number == 199) { //반복문의 아래 조건을 생략하고 반복문의 처음으로 돌아감. continue; } if (number > 0) { System.out.println("양수입니다."); } else if (number < 0) { System.out.println("음수입니다."); } else { System.out.println("0입니다."); } } }
 
 
위의 코드에서 break 와 continue 조건을 추가했다.
입력값으로 198 을 입력하게 되면 반복문이 종료되며, 199을 입력하면 재입력할 수 있도록 설정했다.
 
notion image
 
198을 입력했을 때 break 실행되면서 반복문이 종료된다.
 
notion image
 
199을 입력했을 때 continue 가 실행되면서 아래 코드를 무시하고 반복문의 처음으로 되돌아간다.
Share article
RSSPowered by inblog