자바(Java)학습/1_Java 기초

18.반복문(do-while문)

thespeace 2021. 8. 20. 18:10
  • while문은 조건을 먼저 체크하고 반복 수행이 된다면, do‐while은 조건과 상관 없이 한번은 수행문을 수행하고 나서 조건을 체크
  • 조건이 맞지 않으면(true가 아니면) 더 이상 수행하지 않는다
  • while과는 다르게 do-while문은 while(조건식) 다음에 ' ; ' 세미콜론을 마지막에 꼭 적어줘야 한다
  • 많이 사용하는 문법은 아니지만 가끔 유용할때가 있다

 

do {
   수행문 1;
   ...
} while(조건식);
   수행문 2;
   ...

do while문

 

 

do‐while 예제 : 입력 받는 모든 숫자의 합을 구하는 예제.

단, 입력이 0이 되면 반복을 그만하고 합을 출력

 

package 18;

import java.util.Scanner;

public class DoWhileTest {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int input;
		int sum = 0;
		
		input = scanner.nextInt();
		
		while(input != 0) {
			sum += input;
			input = scanner.nextInt();
		}
		System.out.println(sum);
	}
}

//Console : 1
//	    2
//          3
//          4
//          5
//          0 //종료
            
//          15//1+2+3+4+5=15

package 18;

import java.util.Scanner;

public class DoWhileTest {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int input;
		int sum = 0;
		//input = scanner.nextInt();
		do {
			input = scanner.nextInt();
			sum += input; //sum=sum+input;
		}while(input != 0);
		/*while(input != 0) {
			sum += input;
			input = scanner.nextInt();
		}*/
		System.out.println(sum);
	}
}

//Console : 1
//	    2
//          3
//          4
//          5
//          0 //종료
            
//          15//1+2+3+4+5=15