본문 바로가기
자바

자바 while 문 [북붙따라하기]

by 세상 모든 것 들은 그 자신을 위해 존재한다. 2020. 12. 28.

자바 while문 사용 예제) 코드를 복붙 하여 실행해 보시기 바랍니다. 설명은 코드 아래 부분에 있습니다.

 

--------------------------------------------------------------

 

import java.util.Scanner;

public class Sample {

	public static void main(String[] args) {

		// 입력 받은 숫자가 7 일때 까지 반복해서 "숫자 7을 주세요" 를 출력하는 while문 예제 입니다.
		Scanner scanner = new Scanner(System.in);	//입력받기 위해 생성
		boolean booTrue = true;	//while문을 무한 반복해줄 true값을 가진 불린형 변수
		int nInput;
		
		while(booTrue) {
		
			System.out.print("숫자 7 을 주세요 : "); //입력 대기 문자
			
			nInput = scanner.nextInt();	// 정수를 입력받아서
			
			if(nInput==7) {	//입력받은 정수가 7이면
				
				System.out.println("7 입력  감사합니다. while문을 종료 합니다.  ");
				booTrue =  false ;	//불린형 변수 booTrue 에 flase를 대입해 반복문을 끝낸다.
				
			}
		}
	}
}

 

------------------------------------------------------------------------------------------------------------

 

자바 뿐만 아니라 모든 프로그래밍 언어에서

while 문은 for 문과 함께 대표적인 반복문입니다.

구성:

 

while( 조건문 ){
	
    반복실행할 부분이 들어가는 자리 ;
    
}    

 

실행 순서1. 조건문이 참 이면 아래의 반복 실행할 부분이 실행되는 구조입니다.2. 조건문이 거짓 이면  while문이 종료됩니다.

 

보통 일정 조건까지를 반복하고 싶을 때는 for문을 많이 사용하고돌발적인 상황까지 반복할 때는 while문을 많이 사용합니다.위의 예제처럼 원하는 입력을 기다릴 때나 네트워크로 데이터를 주고받을 때 많이 사용됩니다.

 

눈보다는  키보드가  실력 향샹에 도움이 됩니다.

 

아래는 실전 예제 입니다.

 

// 무한루프의 시작
			while(true) {
			
				System.out.printf("Server-- 서버 시작 [%s:%d]\n", strListenIP, nListenPort);
				System.out.printf("Server-- 접속자 수 = [%d]\n", im.getClientCnt());
				
				sockChild = sockSvr.accept(); // Listen & Accept
				sockChild.setSoLinger(true, 0);

				// 접속한 클라이언트 정보 처리
				isaCld = (InetSocketAddress) sockChild.getRemoteSocketAddress();
				System.out.printf(" 접속자는  [%s:%d] 연결됨 !! \n", isaCld.getHostName(), isaCld.getPort());
	
				// 동시 클라이언트 확인
				if(im.getClientCnt()==im.nMaxClient)
				{
					//System.out.printf(" Client Count=[%d]\n", im.getClientCnt());
					sockChild.close();
					System.out.printf(" 새로운 접속자 (%s:%d) \n"
							,isaCld.getHostName(), isaCld.getPort());
					System.out.println();
					continue;
				}
				
				// 차일드 소켓에 대한 이관 처리
				//sockChild.close();
				String strChildName=String.format("CHILD-%s-%d"
						,isaCld.getHostName(), isaCld.getPort());
				TCPSvrChild3 svrChild=new TCPSvrChild3(
						strChildName, sockChild, isaCld, im);
				svrChild.start();
				im.incClientCnt();
				System.out.printf("Server-- 접속자 수 =[%d]\n", im.getClientCnt());
				
				System.out.println();
				
			} // end of while
			// 무한루프의 범위	

 

 

 

 

 

 

 

728x90
반응형

댓글