制御文-条件文(if,switch)

65499 ワード

JAVAの制御文

  • プログラムのストリーム変更(+特定の条件)
  • 1.if~else条件文


    1.if,if~else条件文


    構文1:
    if(条件式){0}
    条件式がtrueの場合に実行する文//boolean type
    ...
    }
    構文2:
    if(条件式){0}
    条件式がtrueの場合に実行される文.
    ...
    } else {
    条件式がfalseの場合に実行される文.
    ...
    }
    public class If01Main {
    
    	public static void main(String[] args) {
    		System.out.println("if 조건문");
    
    		int num = 10;
    		if(num < 0) {
    			System.out.println("음수입니다");
    		}
    			
    		
    		int num3 = 124;
    		if(num3 % 2 == 0) {
    			System.out.println("짝수입니다");
    		} else {
    			System.out.println("홀수입니다");
    		}
    		
    		
    		System.out.println("\n 조건식 (범위)");
    		int score = 101;
    		
    		// if(0 <= num4 <= 100) <-- 자바는 이런 표현식 없음 / 파이썬은 있음
    		if(0 <= score && score <= 100) {
    			System.out.println(score + "유효한 점수 입니다");
    		} else {
    			System.out.println(score + "는 유효하지 않은 점수입니다");
    		}
    		
    		System.out.println("\n프로그램 종료");
            
    	} // end main()
    
    } // end class
    

    2.if~elseif~else条件式

  • 構文3:
    if(条件式1){0}
    条件式1がtrueの場合に実行される文(複数)
    ...
    }else if(条件式2){
    条件式1はfalse
    条件式2がtrueの場合に実行される文(複数)
    ...
    }else if(条件式3){
    条件式2はfalse
    条件式3がtrueの場合に実行される文(複数)
    ...
    } else {
    以上のすべての条件式がfalseの場合に実行される文です.
    ..
    }
  • public class If02Main {
    
    	public static void main(String[] args) {
    		System.out.println("if - else if - else");
    		
    		int kor = 75, eng = 80, math = 83;
    		int total = kor + eng + math;
    		int avg = total / 3;	// 소수점 버림
    		
    		System.out.println("평균: " + avg);
    		
    		// 1. 평균이 90점 이상이면 A학점 (평균: 90 ~ 100)
    		// 2. 평균이 80점 이상이면 B학점 (평균: 80 ~ 89)
    		// 3. 평균이 70점 이상이면 C학점 (평균: 70 ~ 79)
    		// 4. 평균이 60점 이상이면 D학점 (평균: 60 ~ 69)
    		// 5. 평균이 60점 미만이면 F학점
    		
    		
    		if(avg >= 90) {
    			System.out.println("학점: A");
    		} else if(avg >= 80) {
    			System.out.println("학점: B");
    		} else if(avg >= 70) {
    			System.out.println("학점: C");
    		} else if(avg >= 60) {
    			System.out.println("학점: D");
    		} else {
    			System.out.println("학점: F");
    		}
    		
    
    		System.out.println("\n프로그램 종료");
    	} // end main()
    
    } // end class
    [練習問題]
    package 선택제어문.자가진단08;
    
    import java.util.Scanner;
    
    public class Main {
    
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    
    		double score = sc.nextDouble();
    				
    		if (score >= 4.0) {
    			System.out.println("scholarship");
    		} else if (score >= 3.0) {
    			System.out.println("next semester");
    		} else if (score >= 2.0) {
    			System.out.println("seasonal semester");
    		} else {
    			System.out.println("retake");
    		}
    		
    		sc.close();
     	}
    
    }

    3.3項演算子の条件式

  • 3項演算子(ternary演算子)
    (条件式)?選択1:2/被演算子3個、演算子3個を選択
    (条件式)がtrueの場合は、1を選択します.
    (条件式)がfalseの場合は、2を選択します.
  • public class If04Main {
    
    	public static void main(String[] args) {
    		System.out.println("if 문과 삼항 연산자");
    		
    		int num1 = 145;
    		int num2 = 123;
    		int big;	// 둘 중에서 큰값을 담아보기
    		
    		big = (num1 > num2) ? num1 : num2;
    		System.out.println("더 큰 수 : " + big);
    
    		
    		System.out.println("\n두 수의 차");
    		int num3 = -22;
    		int num4 = -44;
    		int diff = (num3 > num4) ? (num3 - num4) : (num4 - num3);
    		System.out.println("두 수의 차 : " + diff);
    		
    		
    		System.out.println("\n프로그램 종료");
    	} // end main()
    
    } // end class
    

    4.ネストif(nested-if)文


    条件文内の条件文
    public class If05Main {
    
    	public static void main(String[] args) {
    		System.out.println("중첩된 if (nested-if) 문");
    		
    		int num = 98;
    		
    		if(num % 2 == 0) {
    			System.out.println("짝수");
    			
    			if(num % 4 == 0) {
    				System.out.println("4의배수");
    			} else {
    				System.out.println("짝수이지만 4의 배수는 아닙니다");
    			}
    			
    		} else {
    			System.out.println("홀수");
    			
    			if(num % 3 == 0) {
    				System.out.println("3의 배수");
    			} else {
    				System.out.println("홀수이지만 3의 배수는 아닙니다");
    			}
    			
    		}
    		
    		System.out.println("\n프로그램 종료");
            
    	} // end main()
    [練習問題]
    package 선택제어문.자가진단06;
    
    import java.util.Scanner;
    
    public class Main {
    
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    				
    		char gender = sc.next().charAt(0);
    		int age = sc.nextInt();
    		
    		if (gender == 'F') {
    			if (age >= 18) {
    			System.out.println("WOMAN");
    			} else {
    				System.out.println("GIRL");
    			}
    			
    		} else if(gender == 'M') {
    			if(age >= 18) {
    			System.out.println("MAN");
    			} else {
    			System.out.println("BOY");
    			}
    
    		}
    	
    		sc.close();
    		
    	}	// end main()
    	
    }	// end class()

    5.String比較、char比較

  • 文字列
  • を絶対に使用しないでください.
  • 文字列比較equals()、equalsIgnoreCase()!
  • 文字のデフォルト値は整数(アスキーコード値)で、通常の算術
  • と比較できます.
    public class If07Main {
    
    	public static void main(String[] args) {
    		System.out.println("String 비교, char 비교");
    	
    		String str1 = "john";
    		String str2 = "jo";
    		str2 += "hn";
    		
    		System.out.println("str1 = " + str1);
    		System.out.println("str2 = " + str2);
    		
    		// 문자열 비교는 절대로 == 를 사용하지 말자
    		if(str1 == str2) {
    			System.out.println("== 같습니다");
    		} else {
    			System.out.println("== 다릅니다");
    		}
    		
    		
    		// 문자열 비교는 equals() 사용!
    		if(str1.equals(str2)) {
    			System.out.println("equals() 같습니다");
    		} else {
    			System.out.println("equals() 다릅니다");
    		}
    		
    		System.out.println("\n프로그램 종료");
    	} // end main()
    
    } // end class
    

    2.switch~case条件文


    1.switch(条件値)case


    switch(条件値){
    ケース値1:
    ...
    ケース値2:
    ...
    default:
    ...
    }
  • は、breakに遭遇するまで、対応する条件のケース文を検索し、そこから実行を開始します.
  • breakに遭遇した場合、switch文を終了します.
  • がない場合はdefault文が実行されます.
    ※すべてのswitch条件文はif-else if-elseに変換できます.
  • public class Switch01Main {
    
    	public static void main(String[] args) {
    		System.out.println("switch 문");
    
    		int num = 1;
    		
    		switch(num) {
    		case 1:
    			System.out.println("하나");
    			System.out.println("ONE");
    			break;
    		
    		case 2:
    			System.out.println("둘");
    			System.out.println("TWO");
    			break;
    			
    		case 3:
    			System.out.println("셋");
    			System.out.println("THREE");
    			break;
    			
    		default:
    			System.out.println("몰라요~");
    		}
    		
    		System.out.println();
    		// 모든 switch 조건문 if - else if - else로 바꿀 수 있다.
    		// TODO
    		
    		System.out.println("\n프로그램 종료");
    	} // end main()
    
    } // end class
    [例1]
    package com.lec.java.switch02;
    
    public class Switch02Main {
    
    	public static void main(String[] args) {
    		System.out.println("switch 연습");
    
    		// 도전
    		// switch ~ case 조건문을 사용해서
    		// 짝수 이면 --> "짝수입니다"  출력
    		// 홀수 이면 --> "홀수입니다"  출력
    
    		int num = 99;
    		
    		switch(num % 2) {
    		case 0:	// 짝수
    			System.out.println("짝수입니다");
    			break;
    			
    		case 1:
    			System.out.println("홀수입니다");
    			break;
    		}
    		
    		
    		System.out.println("\n프로그램 종료");
    	} // end main()
    
    } // end class

    2.switch(条件){case 1:case 2:}

  • (条件)に従って、対応するケース
  • に移動する.
  • (条件)で使用可能なデータ型は、次のとおりです.
  • intタイプに変換可能:byte、short、int、char
  • enumタイプ(enumリファレンスバージョンはJava 5)
  • Stringタイプ(Java 7バージョンから提供)
  • [例1:文字タイプ]
    public class Switch03Main {
    
    	public static void main(String[] args) {
    		System.out.println("switch 제약 조건");
    		System.out.println("char를 switch문에서 사용");
    
    		char ch = 'C';
    		switch(ch) {
    		case 'a':
    			System.out.println('A');
    			break;
    		case 'b':
    			System.out.println('B');
    			break;
    		case 'c':
    			System.out.println('C');
    			break;			
    		default:
    			System.out.println("몰라요");	// 몰라요 출력. 대/소문자 구별하기 때문
    		}
    		
    		
    		// switch(조건) 에 사용할수 없는 값들
    //		long num = 1;	// 에러 발생. Cannot switch on a value of type long. Only convertible int values, strings or enum variables are permitted.
    //		switch(num) {
    //		
    //		}
    
    		System.out.println("\n프로그램 종료");
    	} // end main()
    	
    } // end class
    [例2:String Type]
    package com.lec.java.switch04;
    
    public class Switch04Main {
    
    	public static void main(String[] args) {
    		System.out.println("String 타입을 switch에서 사용하기");
    		
    		String language = "C++";
    		
    		switch(language) {
    		case "Java":
    			System.out.println("Hello, Java!");
    			break;
    		
    		case "C++":
    			System.out.println("Hello, C++");
    			break;
    			
    		case "Kotlin":
    			System.out.println("Hello, Kotlin");
    			break;
    			
    		default:
    			System.out.println("많은 개발 언어가 있습니다.");
    		
    		}
    
    		System.out.println("\n프로그램 종료");
    	} // end main()
    
    } // end class
    [例3:enumタイプ]
  • enumタイプを定義します.
    Enum名{}
  • enumタイプ定義のメソッドでは実行できません.

  • new -> enum


  • enum: Country.java
  • package com.lec.java.switch05;
    
    // enum : 나열된 값들을 표현하는 타입(객체)
    // 	(enumeration)
    public enum Country {
    	KOREA, JAPAN, USA, CHINA, RUSSIA
    }
    
  • class : Switch05Main. java
  • public class Switch05Main {
    	
    	enum Days {SUN, MON, TUE, WED, THU, FRI, SAT}	// 안에서도 정의 가능	
    	enum Numbers {ONE, TWO, THREE}
    
    	public static void main(String[] args) {
    		System.out.println("enum 타입을 switch에서 사용하기");
    		
    		Country cnt1, cnt2;
    		cnt1 = Country.KOREA;
    		cnt2 = Country.USA;
    		
    		System.out.println(cnt1);
    		System.out.println(cnt2);
    		
    //		System.out.println(cnt1 + 1);	// 불가
    		
    		System.out.println(cnt1 + "Hello");
    		
    		Days day1 = Days.THU;
    		Days day2 = Days.MON;
    
    		switch(day1) {
    		case SUN:	// enum 타입을 사용하는 switch 에선 enum 타입명을 생략
    			System.out.println("일요일");
    			break;
    
    		case MON:
    			System.out.println("월요일");
    			break;
    			
    		case TUE:
    			System.out.println("화요일");
    			break;
    			
    		case WED:
    			System.out.println("수요일");
    			break;
    			
    		case THU:
    			System.out.println("목요일");
    			break;
    			
    		case FRI:
    			System.out.println("금요일");
    			break;
    			
    		case SAT:
    			System.out.println("토요일");
    			break;
    		}
    		
    		System.out.println("\n프로그램 종료");
    	} // end main()
    
    } // end class