[Java] 5.6. while문

김주희's avatar
Feb 05, 2025
[Java] 5.6. while문
💡
형광등처럼 언제 종료될 지 모르는 반복문
→ 종료는 break로 한다.
 
while = 데몬 프로그램

1. 합 구하기 예제

package ex03; import java.util.Scanner; public class GetSum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int sum = 0; // 1, 2, 3, 4, 5, 6 ,7 ,8 ,9 ,10 while (true) { // 1. 숫자 받기 int value = sc.nextInt(); // 2. 종료 신호 확인하기 if (value == -1) { break; // 종료시키는 것 = 인터럽트 (안에서) <-> 스레드 (바깥에서) } // 3. 값 누적하기 sum = sum + value; } System.out.println("누적 값은: " + sum); } }
notion image
 

2. 평균 구하기 예제

package ex03; import java.util.Scanner; public class Average { public static void main(String[] args) { int total = 0; int count = 0; Scanner sc = new Scanner(System.in); while (true) { System.out.print("점수를 입력하시오: "); int grade = sc.nextInt(); if (grade < 0) { break; } total = total + grade; count++; } System.out.println("평균은 " + (total / count)); } }
notion image
Share article

jay0628