본문 바로가기
Hello World/JAVA

JAVA - Control Statements 제어문 - 조건문 if, else, else - if , case, break / Math.random() [개발스터디 기몬]

by 기몬 2023. 3. 3.
728x90
반응형


review time
부호/ 증감 연산자
산술연산자
오버플로우 언더플로우
정확한 계산은 정수 연산으로
/ 실수는 오류의 확률이 크다.
나눗셈 연산 후 NaN와 Infinity 처리
비교연산자
논리연산자
비트논리연산자
비트이동연산자
대입연산자
삼항(조건)연산자
연산의 방향과 우선순위

나눗셈 연산 후 NaN와 Infinity 처리

NaN
= Not a Number, NaN
NaN은 잘못된 입력으로 인해 계산을 할 수 없음을 나타내는 기호이다.
이를테면 음수의 제곱근을 구하려고 한다거나,
일부 언어에서는 0으로 나눈 몫을 구하려고 할 때 예외를 던지는 대신
 NaN을 반환하기도 한다.

컴퓨터 연산에서 NaN은 연산 과정에서 잘못된 입력을 받았음을
나타내는 기호이다. 특히 부동소수점 연산에서 사용한다.
예를 들면 음수의 제곱근을 구하려고 하거나, 0으로 나누려고 했을 때 발생한다

Is NaN an infinity?
In floating-point calculations, NaN is not the same as infinity,
although both are typically handled as special cases in floating-point
representations of real numbers as well as in floating-point operations.

Double.POSITIVE_INFINITY
Double.NEGAIVE_INFINITY
Double.isINFINITY
Double.isNaN
Double.NaN


삼항연산자
조건식 ? 값또는 연산식 : 값또는 연산식

jshell> int num = (int)(Math.random()*100) - 50
-50 부터 49까지 랜덤번호가 출력.

========================================

조건문과 반복문 :  제어문
코드실행 흐름을 제어하는 제어문에는 조건문과 반복문이 있다
특정한 조건에 환경과 조건에 따라 코드를 실행하게 하는 조건문에는 if, switch 가 있다.
특정한 조건에 반복되는 코드를 실행하게 하는 반복문에는 for, while, do while이 있다.

java control statements

What are the control statements in Java?
java control statements
A control statement in java is a statement that determines whether
the other statements will be executed or not. It controls the flow of a program.
An 'if' statement in java determines the sequence of execution
between a set of two statements.


코드 실행 흐름 제어
- 실행 흐름 : main() 메소드의 시작 중괄호 ({)에서 끝중괄호 (})까지 위부터 
아래로 실행되는 흐름
- 흐름 제어문 : 실행 흐름을 개발자가 원하는 뱡향으로 바꿀수 있도록 해주는 것
- 루핑 : 반복문이 실행 완료된 경우 제어문 처음으로 다시 되돌아가 반복 실행되는 것

if 문
조건에 따라 실행되는 if문
- if 문 : 조건식의 결과에 따라 블록 실행 여부가 결정
- 조건식에는 true 또는 false 값을 산출할 수 있는 연산식이나 boolean 변수가 올 수 있음
- 조건식이 true이면 블록을 실행하고 false이면 블록을 실행하지 않음 
- if-else문 : 조건식이 true이면 if 문 블록이 실행되고, false 이면 else 블록이 실행

switch 문
변수값에 따라 case를 실행하는 switch문 
- switch 문 : 괄호 안의 변수값에 따라 해당 case로 가서 실행문을 실행.
- 변수값과 동일한 값을 갖는 case가 없으면 default로 가서 실행문을 실행하며, default 생략 가능.
- break는 다음 case를 실행하지 않고 switch 문을 빠져나갈 때 사용
- break가 없다면 다음 case가 연달아 실행

for 문
실행문을 반복하는 for문
- for 문은 실행문을 여러 번 반복 실행해주기 때문에 코드를 간결하게 만들어 줌
- 1. 초기화식이 제일 먼저 실행 / 2. 조건식을 평가해서 true 이면 / 3. 실행문을 실행시키고 false이면
for 문을 종료하고 블록을 건너뜀
- 2. 조건식이 true가 되어 / 3. 실행문을 모두 실행하면 / 4. 증감식이 실행
- 다시 2. 조건식을 평가. 평가 결과가 다시 true이면 3. / 4. / 2.로 다시 진행하고, false이면 for 문 끝남
- 초기화식에서 부동 소수점을 쓰는 float 타입을 사용하지 않도록 주의

               

                 for (1.초기화식; 2.조건식; 4.증감식) {
                                         3.실행문;
                 }

초기화문 (딱 한번 수행됨. )



while 문 
조건식에 따라 실행문을 반복하는 while 문
- 조건식이 true 일 경우에 계속해서 반복하고 , false가 되면 반복을 멈추고 while 문을 종료
- while 문이 처음 실행될 때 1. 조건식을 평가 . 평가 결과가 true이면/ 2. 실행문을 실행한다.
- 2. 실행문이 모두 실행되면 조건식으로 되돌아가서 1. 조건식을 다시 평가. 
다시 조건식이 true라면 2. / 1. 로 진행하고, false라면 while 문을 종료.
- 조건식에 true 를 사용하면 while(true) {...} 가 되어서 무한 반복. 
이 경우 while 문을 빠져나가가기 위한 코드 필요

 

                 while (1. 조건식) {

                                 2. 실행문;
                 }

do-while 문
실행 결과에 따라 실행문을 반복하는 do-while 문
- 블록 내부를 먼저 실행시키고 실행결과에 따라서 반복 실행을 계속할지 결정
- 작성 시 while() 뒤에 반드시 세미콜론(;)을 붙여야 하는 데 주의
- do-while 문이 처음 실행될 때 1. 실행문을 우선 실행한다. 1. 실행문이 모두 실행되면 2. 조건식을 평가
- 평가 결과가 true이면 1. -> 2. 와 같이 반복 실행하고, 조건식의 결과가 false이면 do-while 문을 종료한다. 

 

                  do {
                               1. 실행문;


                  } while ( 2. 조건식);


break 문 
제어문을 종료하는 break 문 
- 반복문인 for문, while 문, do-while 문을 실행 중시하거나 조건문인 switch 문을 종료할 때 사용
- break 문은 대게 if 문과 같이 사용되어 조건식에 따라 for 문과 while 문을 종료

cuntinue 문
조건식으로 이동하는 continue문 
- 반복문인 for 문 , while 문, do-while 문에서만 사용
- 블록 내부에서 continue 문이 실행되면 for 문의 증감식 또는 while 문, 
do-while 문의 조건식으로 바로 이동
- break 문과 달리 반복문을 종료하지 않고 계속 반복을 수행
- 대개 if 문과 같이 사용되며, 특정 조건을 만족하는 경우에 continue 문을 실행해서 그 이후의 
문장을 실행하지 않고 다음 반복으로 넘어감

 



조건문
if 문 , switch 문

반복문
for 문, while 문, do-while 문

조건에 따라 실행되는 if 문
 - if 문 : 조건식의 결과에 따라 블록 실행 여부가 결정
 - 조건식에는 true 또는 false 값을 산출할 수 있는 연산식이나
boolean 변수가 올 수 있음
 - 조건식이 true 이면 블록을 실행하고 false이면 블록을 실행하지 않음
 - if-else 문 : 조건식이 true이면 if 문 블록이 실행되고,
   false이면 else 블록이 실행

모든 연산자는 연산을 하기 위해 타입을 일치 시켜야 한다.
실행문에서 두개의 문자열로 합쳐주는 것이 컴팩트 메이트 (+)
실행문 + 는 부호의 연산자에서의 단항 연산자
이항 연산자에서 실수 덧셈 그리고
마지막으로 문자열의 연결을 진행하는 것.
ex )   System.out.println(num + "은 홀수 입니다.");

몬테카를로 시뮬레이션 (Monte Carlo Simulation)
몬테카를로 시뮬레이션은 불확실한 사건의 가능한 결과를 예측하는 수학적 기법.
컴퓨터 프로그램은 이 방법을 사용하여 과거 데이터를 분석하고 조치 선택에 따라
다양한 미래 결과를 예측.

public class IfStatementExample {
	
	public static void main(String[] args) {
		int score = (int)(Math.random()*50) + 51;
		
		if ( 90 <= score ) 
			System.out.printf("%3d ==> A", score);
			else if ( 80 <= score)
				System.out.printf("%3d ==> B", score);
			else if ( 70 <= score)
				System.out.printf("%3d ==> C", score);
			else if ( 60 <= score)
				System.out.printf("%3d ==> D", score);
				else 
					System.out.printf("%3d ==> F", score);
		
	}	// 코드를 간소화시키고 최적화함. 필요하지 않은 코드를 삭제하고 최소화 시킨다.
	
	public static void main7(String[] args) {
		int score = (int)(Math.random()*50) + 51;
		
		if ( 90 <= score && score <= 100) 
			System.out.printf("%3d ==> A", score);
		
			else if ( 80 <= score && score <= 90)
				System.out.printf("%3d ==> B", score);
			else if ( 70 <= score && score <= 80)
				System.out.printf("%3d ==> C", score);
			else if ( 60 <= score && score <= 70)
				System.out.printf("%3d ==> D", score);
			else if ( 0 <= score && score <= 50)
				System.out.printf("%3d ==> F", score);
			
	}	// else if를 사용해서 참이되는 블럭 하나를 수행하고 종료한다. (상호배타적)
	
	public static void main6(String[] args) {
//		int score = (int)(Math.random()*101);
		int score = (int)(Math.random()*50) + 51;
		
		if ( 90 <= score && score <= 100) 
			System.out.printf("%3d ==> A", score);
		
		if ( 80 <= score && score <= 90) 
			System.out.printf("%3d ==>B", score);
		
		if ( 70 <= score && score <= 80) 
			System.out.printf("%3d ==>C", score);
		
		if ( 60 <= score && score <= 70) 
			System.out.printf("%3d ==>D", score);
		
		if ( 50 <= score && score <= 60) 
			System.out.printf("%3d ==>E", score);
		
		if ( 40<= score && score <= 50) 
			System.out.printf("%3d ==>F", score);
	}		// 코드는 작성했지만 비효율적인 작성법... 
	
	public static void main5(String[] args) {
		int num = (int)(Math.random()*100);
		
		if (num%2 == 0) { // 출력문 statement가 두개 이상이면 반드시 {} 블럭 안에 작성해야 한다. 
			System.out.println("###");
			System.out.println("even");
			System.out.println("###");
		}
		else
			System.out.println("###");
			System.out.println("odd");
	}	// if - else 문 : 둘중 하나는 반드시 수행이 된다 _ 조건식에 따라 참과 거짓으로 수행이 됨.
	
	public static void main4(String[] args) {
		int num = (int)(Math.random()*100);
		
		if (num%2 == 0)
			System.out.println(num + " is even.");
		// 하나의 statement일 때는 {} 생략이 가능하다. 
		
		if (num%2 == 1)
			System.out.println(num + " is odd.");
	}

	public static void main3(String[] args) {
		
		System.out.println(System.currentTimeMillis());
		System.out.println(Math.random());
		
		int num = (int)(Math.random()*10) + 1 ;		// [1 - 10]
		
		if (num%2 == 0) {
			System.out.println("### even");
			System.out.println(num + "은 짝수 입니다.");
		}
		
		if (num%2 == 1) {
			System.out.println("### odd");
			System.out.println(num + "은 홀수 입니다.");
		}
		
		System.out.println("Program End.. ");
//		System.out.println(num);
	}
	
	public static void main2(String[] args) {
		boolean b = true;
		int a = 3;
		int c = 4;
		
		
		if (b) {
			System.out.println("It works when ifstatement is true.. ");
		}

		if (a > c) {
			System.out.println("It works when ifstatement is true...");
			
		}
	}

}


if 문에는 조건식이 온다 true or false. (관계연산자, 논리연산자)

if 문이 한줄일 때는 {블럭} 을 생략하기도 한다. // 제어문이 하나일 때는 모든 제어문 공통.
- 출력문 statement가 두개 이상이면 반드시 {} 블럭 안에 작성해야 한다.  

if 에 두 가지 조건을 제시할 때는 else를 사용한다.
조건식의 참 if , 조건식이 거짓일 때 수행을 만드는 조건식은 else
if - else  / else if
if - else 문 : 둘중 하나는 반드시 수행이 된다 _ 조건식에 따라 참과 거짓으로 수행이 됨.

else if를 사용해서 참이되는 블럭 하나를 수행하고 종료한다. (상호배타적)

switch 문 :  switch case break default

 

public class SwitchStatementExample {

	public static void main(String[] args) {
		int num = 1;
		
		switch(num) {	// 정수	
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			break;
		case 3: 
			System.out.println("three");
			break;
		default:
			System.out.println("default");
		}
	
	}

}

 

 

public class RandomExample {

	public static void main(String[] args) {
		char ch = ' ';
		
		switch ((int)(Math.random()*5)) {
		case 0, 3 -> ch = (char)(Math.random()*10 +'0');
		case 1, 4 -> ch = (char)(Math.random()*26 +'A');
		case 2 -> ch = (char)(Math.random()*26 +'a');
		
		}
		
		System.out.println("ch = " + ch);
		
		if (ch >= '0' && ch <= '9')
			System.out.println("Number");
		else if (ch >= 'A' && ch <= 'Z')
			System.out.println("Uppercase");
		else
			System.out.println("Lowercase");
		
	}
	
	public static void main4(String[] args) {
		char ch = ' ';	 // 변수 초기화.
		
		switch ((int)(Math.random()*5)) {
		case 0:				//switch case fall through
		case 3:
			ch = (char)(Math.random()*10 + '0');
			break;
		case 1:
		case 4:
			ch = (char)(Math.random()*26 + 'A');
			break;
		case 2:
			ch = (char)(Math.random()*26 + 'a');
		default:
			break;
		}
		
		System.out.println("ch = " + ch);
		
		if (ch >= '0' && ch <= '9')
			System.out.println("Number");
		else if (ch >= 'A' && ch <= 'Z')
			System.out.println("Uppercase");
		else
			System.out.println("Lowercase");
	}
	
	public static void main3(String[] args) {
		
		int group = (int)(Math.random()*3);
		char ch ;
		
		if (group==0)
			ch = (char)(Math.random()*10 +'0');
		else if (group==1)
			ch = (char)(Math.random()*26 + 'A');
		else
			ch = (char)(Math.random()*26 + 'a');
		
		System.out.println(ch);
	}
	
	
	public static void main2(String[] args) {
		
		int group = (int)(Math.random()*3);
		char ch = group==0 ? (char)(Math.random()*10 + '0') : 
					group==1 ? (char)(Math.random()*26 + 'A'):
								(char)(Math.random()*36 + 'a');
		
		System.out.println(ch);
		
	}
	
	public static void main1(String[] args) {	// 대문자/소문자 알파벳, 숫자 랜덤 생성. 
//		char ch = (char)((Math.random()*26) + 'A');
//		char ch = (char)((Math.random()*26) + 'a');
		char ch = (char)((Math.random()*10) + '0');
		System.out.println(ch);
	}

}

 

반복문 for문 예습 

윤년, 평년 구하기. 

public class YeapExample {

	public static void main(String[] args) {
		
		for (int year=1; year<2030; year++ ) {
			if (year%4==0 && year%100!=0 || year%400==0)
				System.out.printf("%04d == 윤년****\n" , year);
			else 
				System.out.printf("%04d == 평년\n" , year);
			
		}
		
	}

}
728x90
반응형

댓글