웹_프론트_백엔드/JAVA프레임윅기반_풀스택

2020.03.23

shine94 2020. 3. 23. 09:03

1. 객체지향프로그래밍(Object-oriented programming, OOP)
 : 사람의 사고와 비슷한 형태의 프로그래밍

1) 장점

 ① 신뢰성 있는 소프트웨어를 작성할 수 있다.
 ② 코드 재활용하기 쉽다.
 ③ 업그레이드가 쉽다.
 ④ 디버깅이 쉽다.

2) 단점
 ① 실행 크기  
 ② 실행 속도


2. 절차적 프로그래밍 (Procedural programming)
 : 물 흐르듯이 순서대로 처리하는 프로그래밍


3. 객체 (Object)
 : 우리 생활에서 이해하고, 인지할 수 있는 대상


4. 클래스 (Class)
 : 객체를 청사진화, 설계도화


5. 인스턴스 (Instance)

 : 클래스를 통해 실제로 만들어진 객체(들)

 

 

6. 생성자(Alt + Shift + S + O), getter & setter(Alt + Shift + S + R)

 

[실습코드]

 

1. [과제] 가위바위보 게임

package practice.rockscissorpaper;

import java.util.Scanner;
/*
	 간단한 가위, 바위, 보 게임을 만듭니다.
	(실행화면은 다음 페이지에)
	
	showMenu / inputChoice / displayChoice
	/ computeResult  메소드들을 어떻게 
	구현해볼수 있을까요? 
	
	
	main() 메소드는 오른쪽과 같이 구성하고
	변경하지 않는 상태에서
	나머지 메소드들을 구현하여 완성해보세요
	
	필요하다면 클래스의 멤버변수등을 추가해도
	좋습니다
 */
public class RockScissorPaper {

	// 멤버변수가 필요하면 작성하세요.
	
    public static void main(String[] args) {
        System.out.println("가위 바위 보 게임");
        Scanner sc = new Scanner(System.in);
        
        while(true){
            showMenu(); // 메뉴보여주기
 
            int userChoice = inputChoice(sc); // 사용자 입력

            if(userChoice < 0 || userChoice > 3) {
            	System.out.println("잘못입력했습니다.\n다시 입력해주세요~");
            	
            } else {
            	if(userChoice == 0){ break; }	// 0 이면 종료
            	
            	// 컴퓨터 선택:   1 - 가위,  2- 바위,  3 - 보
            	int computerChoice = (int) Math.floor(Math.random() * 3) + 1;  
            	
            	displayChoice(userChoice, computerChoice); // 양측의 선택 보여주기
            	computeResult(userChoice, computerChoice); // 승부결과 보여주기
            }
        }
        
        sc.close();
        
        System.out.println("프로그램이 종료되었습니다~");
    } // end main()
    
    
	// method name: showMenu
	// return: void
	// arguments: none
	// 기능: 유저가 가위/바위/보 선택할 수 있는 메뉴 출력
	public static void showMenu() {
		System.out.println("[가위 바위 보 게임]");
		System.out.println("----------------");
		System.out.println("1] 가위");
		System.out.println("2] 바위");
		System.out.println("3] 보");
		System.out.println("0] 종료");
		System.out.println("----------------");
		System.out.println("선택");
	} // end showMenu()
	
    
	// method name: inputChoice
	// return: int (유저의 가위(1)/바위(2)/보(3) 선택 내용)
	// arguments: Scanner sc (입력장치)
	public static int inputChoice(Scanner sc) {
		int choice = 0;
		choice = sc.nextInt();
		
		return choice;
	} // end inputChoice()

	
	// method name: displayChoice
	// return: void
	// arguments:
	//   1) int user: 유저의 선택(가위(1)/바위(2)/보(3))
	//   2) int com: 컴퓨터의 선택(가위(1)/바위(3)/보(3))
	public static void displayChoice(int user, int com) {
		//displayChoice(userChoice, computerChoice); // 양측의 선택 보여주기
		System.out.println("사용자 vs 컴퓨터");

		System.out.println(getHandType(user) + " vs " + getHandType(com));
		
	} // end displayChoice()
	
	
	// method name: getHandType
	// return: String ("가위"/"바위"/"보")
	// arguments: int choice(1, 2, 3)
	public static String getHandType(int choice) {
		String type = "";

		switch(choice) {
		case 1:
			type = "가위";
			break;
		case 2:
			type = "바위";
			break;
		case 3:
			type = "보";
			break;
		}
		
		return type;
	} // end getHandType()
	
	
	// method name: computeResult
	// return: void
	// arguments:
	//   1) int user: 유저의 선택(가위(1)/바위(2)/보(3))
	//   2) int com: 컴퓨터의 선택(가위(1)/바위(2)/보(3))
	public static void computeResult(int user, int com) {
		//computeResult(userChoice, computerChoice); // 승부결과 보여주기

		switch(user) {
		//가위
		case 1:
			switch(com) {
			//가위, 비김
			case 1:
				System.out.println("비겼습니다.");
				break;
			//바위, 컴 승
			case 2:
				System.out.println("Com Win");
				break;
			//보, 컴 짐
			case 3:
				System.out.println("User Win");
				break;
			}
			break;
		//바위
		case 2:
			switch(com) {
			//가위, 컴 짐
			case 1:
				System.out.println("User Win");
				break;
			//바위, 비김
			case 2:
				System.out.println("비겼습니다.");
				break;
			//보, 컴 승
			case 3:
				System.out.println("Com Win");
				break;
			}
			break;
		//보
		case 3:
			switch(com) {
			//가위, 컴 이김
			case 1:
				System.out.println("Com Win");
				break;
			//바위, 컴 짐
			case 2:
				System.out.println("User Win");
				break;
			//보, 비김
			case 3:
				System.out.println("비겼습니다.");
				break;
			}
			break;
		}
		
	} // end computeResult()

} // end class

 

 

2. [과제] 평균, 분산, 표준편차 구하기

package practice.stddev;

import java.util.Scanner;

public class StdDev {

	public static void main(String[] args) {

		Scanner	sc = new Scanner(System.in);
		
		// 임의정수 5개로 초기화한 정수로
		// 평균, 분산, 표준편차 구하기
		// 직접 입력한 경우
		//int[] num = {175, 177, 179, 181, 183};
		//입력을 받은 경우, 175 177 179 181 183, 81 76 81 55 36
		int[] num = new int[5];
		
		for (int i = 0; i < num.length; i++) {
			num[i] = sc.nextInt();
		}
		
		System.out.println("평균 : " + String.format("%.1f", calcAvg(num)));
		System.out.println("분산 : " + String.format("%.2f", calcVariance(num)));
		System.out.println("표준편산 : " + calcStdDev(num));
		
	} // end main
	
    
	/**
	 * 메소드 이름 : calcAvg
	 * 매개변수 : int []
	 * 리턴값 : double
	 * 
	 * 주어진 배열의 '평균값' 리턴
	 */
	public static double calcAvg(int num[]) {
		int sum = 0;
		double avg = 0.0;
		
		//총합 구하기
		for (int i = 0; i < num.length; i++) {
			sum += num[i];
		}
		
		//평균 구하기
		avg = (double)sum / num.length;
		
		//평균값 리턴
		return avg;
	}
	
    
	/**
	 * 메소드 이름 : calcVariance
	 * 매개변수 : int []
	 * 리턴값 : double
	 * 
	 * 주어진 배열의 '분산값' 리턴
	 */
	public static double calcVariance(int num[]) {
		//num의 배열 개수 구함
		//왜? 그만큼 편차, 편차 제곱 저장할 변수가 필요하기 때문에
		int Length = num.length;
		
		//편차값 저장할 변수
		double[] deviation = new double[Length];
		
		//평균제곱 저장할 변수
		double[] multi = new double[Length];
		
		//분산 저장할 변수
		double Variance = 0.0;
		double sum = 0.0;
		
		//편차구하기(변량 - 평균)
		for (int i = 0; i < num.length; i++) {
			deviation[i] = num[i] - calcAvg(num);
		}
		
		//편차제곱구하기(편차*편차)
		for (int i = 0; i < deviation.length; i++) {
			multi[i] = deviation[i] * deviation[i];
		}
			
		//분산 구하기(편차제곱의 평균)
		//1.편차 제곱 총 합
		for (int i = 0; i < multi.length; i++) {
			sum += multi[i];
		}
		
		//2.편차 제곱 평균
		Variance = sum / multi.length;
		
		return Variance;
	}


	/**
	 * 메소드 이름 : calcStdDev
	 * 매개변수 : int []
	 * 리턴값 : double
	 * 
	 * 주어진 배열의 '표준편차' 리턴
	 */
	//분산 루트값
	public static double calcStdDev(int num[]) {
		double StdDev = 0.0;
		
		//Math.sqrt(): 제곱근, 루트 근사값 구하기
		StdDev = Math.sqrt(calcVariance(num));
		
		return StdDev;
	}

} // end class

 

 

3. [과제] 가장 단어의 개수가 많은 문장 찾기

package practice.maxwords;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
/* MaxWrod
	여러문장으로 구성된 문자열을 입력받은뒤 
	문자열에서 가장 단어의 개수가 많은 문장을 찾아서, 
	그 문장과 문장의 단어의 개수를 출력
	'문장'의 구분은  .(마침표) !(느낌표) ?(물음표) 로 한다.
	'단어'구분은 '공백' 으로 한다
	
	입력예]
	We test coders. Give us a try. Can you make it out? It's awesome.
	
	출력예]
	5개
	Can you make it out
 */
public class MaxWord {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		// We test coders. Give us a try. Can you make it out? It's awesome.
		// 사용자에게 문자 입력받기
		String expr = sc.nextLine();
		
		String[] sentence = sentenceDivision(expr);
		
		int[] wordCount = WordCount(sentence);

		int place = WordCountMAX(wordCount);
		
		// 제일 큰 문장을 출력한다.
		System.out.println(wordCount[place] + "개");
		System.out.println(sentence[place]);
		
		sc.close();
	} // end main
	
	
	// method name: sentenceDivision
	// return: String[]
	// arguments: String expr
	// 기능: 사용자에게 입력 받은 문자열을 문장 단위로 구분하기
	//      문장의 구분은 .(마침표), !(느낌표), ?(물음표)로 구분
	public static String[] sentenceDivision(String expr) {
		// 문장의 구분은 .(마침표), !(느낌표), ?(물음표)로 구분
		StringTokenizer exprTokenizer = new StringTokenizer(expr, ".!?");
		
		// 몇개의 문장으로 쪼개졌는지 개수 파악하기
		// 그래야 각기 문장 별로 String 배열 인덱스 개수를 알 수 있기 때문에
		int count = exprTokenizer.countTokens();
		
		// 구분한 문장을 저장할 String 타입의 sentence 배열
		String[] sentence = new String[count];
		
		// 구분된 문장을 sentence 배열에 담기
		for(int i = 0; i < count; i++) {
			sentence[i] = exprTokenizer.nextToken();
		}
		
		// 맨 앞 공백 제거
		for(int i = 0; i < count; i++) {
			sentence[i] = sentence[i].trim();
		}
		
		// sentence를 메인으로 돌려줘야 함
		return sentence;
	}
	
	
	// method name: WordCount
	// return: String[]
	// arguments: int[]
	// 기능: 문장별로 단어가 몇개나 있는지 개수 파악하기
	public static int[] WordCount(String[] sentence) {
		//어느것이 제일 많은지 저장하기 위해서 각기 sentence 별로 개수 저장하기
		int[] wordCount = new int[sentence.length];
		
		for (int i = 0; i < sentence.length; i++) {
			String[] words = sentence[i].split("\\s+");
			wordCount[i] = words.length;
			
		}

		// 문장별 단어 개수가 저장되어 있는 int[]을 메인으로 돌려줘야 함
		return wordCount;
	}
	
	
	// method name: WordCountMAX
	// return: int[]
	// arguments: int
	// 기능: 가장 큰 문장의 인덱스 값을 찾기
	public static int WordCountMAX(int[] wordCount) {
		// 이때 몇번째 sentence가 제일 큰지 위치를 저장할 변수, 기본 위치 0번째로 저장
		int place = 0;
		
		// 가장 큰 값을 찾기
		for (int i = 0; i < wordCount.length - 1; i++) {
			if(wordCount[i] < wordCount[i + 1]) {
				place = i + 1;
				
			}
		}
        
		// 가장 큰 문장의 인덱스 값이 저장된 int를 메인으로 돌려줘야 함
		return place;	
	}
	
} // end class

 

 

4. Lec_String

1) com.lec.java.regexp01 패키지, RegExp01Main 클래스

package com.lec.java.regexp01;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* 정규표현식 regular expression
 * 
 * 문자열 검색, 치환  등의 동작에 있어서
 * 단순한 '문자열 비교' 를 하는 것이 아니라 
 * 특정 '패턴'과 비교하고자 할때 이를 단 몇줄의 코드로 구현 가능!
 * 주어진 문자열에서 패턴을 찾아내는 것을 '패턴 매칭(pattern matching)' 이라 함
 * 
 * 사용자가 입력한 문자열 패턴 유효성 체크 등에 많이 사용
 * 		ex) 주민등록번호, URL, email, 비밀번호, 
 * 			날짜포맷(yyyy-mm-dd) 
 * 			전화번호(010-xxxx-xxxx) ... 
 * 
 * 자바는 java.util.regex 에서 관련 클래스들 제공
 * 		Pattern, Matcher ..
 * 
 * 일반적인 작성단계
 * 	 1) 주어진 정규표현식을 구현하는 Pattern 객체 생성
 *   2) 패턴 매칭 수행객체 Matcher 생성
 *   3) Matcher 객체로부터 패턴매칭을 수행하여  검색, 치환등의 동작
 * 
 * 장점: 코딩량 저감, 거의 대부분의 언어에서 공용으로 사용.
 * 단점: 처음에 배우기 어렵고, 코드 가독성 떨어뜨림.
 * 
 * 정규표현식을  사용하는 String 메소드들:
 * 	matches(), split(), replaceAll(), replaceFirst()
 * 
 * 정규표현식 연습 사이트 추천
 * : https://regexr.com/    (정규식 , 문자열 매칭 연습)
 * : https://regexone.com/  ( step by step 으로 연습 하기 좋음)
 * : https://regexper.com/  (특징: 시각화, 정규식을 이미지로 다운가능)
 * : https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html  (오라클 공식)
 * ─────────────────────────────────────────────────────────
 *  정규표현식	설명
 *  ^	문자열 시작
 *  $	문자열 종료
 *  .	임의의 문자 [단 ‘'는 넣을 수 없습니다.]
 *  *	앞 문자가 0개 이상의 개수가 존재할 수 있습니다.
 *  +	앞 문자가 1개 이상의 개수가 존재할 수 있습니다.
 *  ?	앞 문자가 없거나 하나 있을 수 있습니다.
 * []	문자의 집합이나 범위를 표현합니다. -기호를 통해 범위를 나타낼 수 있습니다. ^가 존재하면 not을 나타냅니다.
 * {}	횟수 또는 범위를 나타냅니다.
 * ()	괄호안의 문자를 하나의 문자로 인식합니다.
 * |	패턴을 OR 연산을 수행할 때 사용합니다.
 * \s	공백 문자
 * \S	공백 문자가 아닌 나머지 문자
 * \w	알파벳이나 문자
 * \W	알파벳이나 숫자를 제외한 문자
 * \d	[0-9] 숫자
 * \D	숫자를 제외한 모든 문자
 * (?i)	대소문자를 구분하지 않습니다.
 */
public class RegExp01Main {

	public static void main(String[] args) {
		System.out.println("정규표현식 regular expression");
		
		String input;
		String regex;	// 정규 표현식
		Pattern pat;
		Matcher matcher;
		
		System.out.println();
		System.out.println("■ 정규표현식 객체, 메소드 연습");
		System.out.println("패턴] .  ← 임의의 문자 하나");
		
		// 1).주어진 정규표현식을 구현하는 Pattern 객체 생성
		// Pattern.compile(정규표현식 문자열) 사용  

		regex = "My....";	// My로 시작하고 임의의 문자 4개의 패턴
		pat = Pattern.compile(regex);	// Pattern 객체 생성
		
		input = "-My1234-";
		
		
		// 2) 패턴 매칭 수행객체 Matcher 생성
		// Pattern 의 matcher() 사용
		// Pattern을 사용해서 주어진 문자열에서 패턴 매칭할 객체 생성 --> Matcher객체 리턴
		// (아직 패턴 매칭을 진행하진 않았다)
		
		matcher = pat.matcher(input);	// Matcher 생성
		
        
		// 3) Matcher 객체로부터 패턴매칭을 수행하여  검색, 치환등의 동작  
		//  find() '다음' 패턴매칭 검색 , 패턴매칭 발견하면 true 아니면 false 리턴
		//  group() 바로 직전에 패턴매칭된 문자열 String 리턴
		//  reset() 다시 처음부터 패턴매칭하도록 reset 함.
		//  replaceFirst() : 첫번째 매칭을 치환
		//  replaceAll() : 모든 매칭을 치환
		//  matches() : 패턴매칭이 '문자열 전체영역' 이 패턴매칭 되는지 여부
		//  start() : 최근 매칭의 시작 index, 
		//  end() : 최근 매칭의 끝 index (마지막 매칭된 문자 '다음' 인덱스값)
		if(matcher.find()) {
			System.out.println("find() 성공");
			System.out.println("matcher.group() : " + matcher.group() 
				+ "{ " + matcher.start() + " ~ " + matcher.end() + " }");
		} else {
			System.out.println("find() 실패");
		}
		
		// 위의 코드를 다시 실행하면? 다음 패턴 매칭을 시도한다 --> 결과 실패
		if(matcher.find()) {
			System.out.println("find() 성공");
			System.out.println("matcher.group() : " + matcher.group() 
				+ "{ " + matcher.start() + " ~ " + matcher.end() + " }");
		} else {
			System.out.println("find() 실패");
		}
		
		// reset() 다시 처음부터 패턴매칭하도록 reset 함.
		matcher = matcher.reset();
		
		// 다시 시도하면 매칭된다..!
		if(matcher.find()) {
			System.out.println("find() 성공");
			System.out.println("matcher.group() : " + matcher.group() 
				+ "{ " + matcher.start() + " ~ " + matcher.end() + " }");
		} else {
			System.out.println("find() 실패");
		}
		
		// replaceFirst() : 첫번째 매칭 패턴을 치환하여 결과 리턴
		System.out.println(matcher.replaceFirst("XXXX"));
		
		// matches()
		// 패턴매칭이 '문자열 전체영역' 이 패턴매칭 되는지 여부
		System.out.println();
		System.out.println("matches()");
		matcher = pat.matcher("-My1234-");
		if(matcher.matches()) {
			System.out.println("matches() 매칭 ok");
		} else {
			System.out.println("matches() 매칭 FAIL");
		}
		
		matcher = pat.matcher("My1234");
		if(matcher.matches()) {
			System.out.println("matches() 매칭 ok");
		} else {
			System.out.println("matches() 매칭 FAIL");
		}
		
        
		// 위 코드를 아래와 같이 한 번에 만들 수 있다.
		if(Pattern.compile("My....").matcher("My1234").matches()) {
			System.out.println("matches() 매칭 ok");
		} else {
			System.out.println("matches() 매칭 FAIL");
		}
		
		System.out.println();
		System.out.println("Pattern.matches(regex, input) 사용");
		// 단순히 '문자열 전체영역' 이 패턴에 맞는지 여부 만 확인하려면 간단하게 Pattern.matches() 사용하자.
		// Pattern.matches()는 내부적으로 정확히 아래와 같이 동작하게 된다.
		//     Pattern.compile(regex).matcher(input).matches()
		if(Pattern.matches("My....", "Myabcd")) {
			System.out.println("Pattern.matched() 매칭 OK");
		} else {
			System.out.println("Pattern.matched() 매칭 FAIL");
		}
		
		// 대소문자 구분함...!!
		if(Pattern.matches("My....", "myabcd")) {
			System.out.println("Pattern.matched() 매칭 OK");
		} else {
			System.out.println("Pattern.matched() 매칭 FAIL");
		}

		// 임의의 문자 개수가 달라...!!
		if(Pattern.matches("My....", "myabc")) {
			System.out.println("Pattern.matched() 매칭 OK");
		} else {
			System.out.println("Pattern.matched() 매칭 FAIL");
		}
		
		System.out.println();
		System.out.println("■ 여러개 패턴 검색");
		
		// 과연 "My...." 으로 몇개가 매칭되나?  : 예측해보자
		// 기본적으로 대소문자를 구분하여 매칭한다
		input = "-My98KK-myABCD--My1234567--MyZZ---My789";
		matcher = pat.matcher(input);
		
		while(matcher.find()) {
			System.out.println(matcher.group() + "{ " + matcher.start() + " ~ " + matcher.end() + " }");
		} // end while
		
		System.out.println();
		
		System.out.println("matcher.replaceFirst : " + matcher.replaceFirst("***"));
		System.out.println("matcher.replaceAll : " + matcher.replaceAll("***"));
		
		System.out.println();
		System.out.println("find(fromIndex)");  // fromIndex부터 검색

		matcher = pat.matcher(input);
		int fromIndex = 16;
		while(matcher.find(fromIndex)) {
			System.out.println(matcher.group() + "{ " + matcher.start() + " ~ " + matcher.end() + " }");
			fromIndex = matcher.end();	// 이 문장이 없으면 무한 루프 돔
							// 왜냐하면 위 문장이 없으면 계속 16번째부터 시작 > 무한루프
		} // end while
		
		System.out.println("\n프로그램 종료");
	} // end main()

} // end class


2) com.lec.java.regexp02 패키지, RegExp02Main 클래스

package com.lec.java.regexp02;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* 그룹(group) 
 * 정규표현식에 () 을 사용하여  패턴 내에서 '그룹'을 지정 하면
 * () 의 개수만큼 그룹이 만들어진다.
 */
public class RegExp02Main {

	public static void main(String[] args) {
		System.out.println("정규표현식 : group");
		
		String input;
		String regex;
		Pattern pat;
		Matcher matcher;
		
		System.out.println();
		regex = "(My)(....)";  // 정규표현식에 () 사용
		pat = Pattern.compile(regex);
		
		input = "-My98KK-myABCD--My1234567--MyZZ---My789";
		
		matcher = pat.matcher(input);
		
		System.out.println("groupCount() : " + matcher.groupCount());
		
		System.out.println("입력 문자열 : " + input);
		
		while(matcher.find()) {
			System.out.println(matcher.group() + "{ " + matcher.start() + " ~ " + matcher.end() + " }");
			
			// 그룹들 출력해보기
			// group(int group), start(int group), end(int group)
			System.out.println("\t group(0) : " + matcher.group(0) 
				+ " { "  + matcher.start(0) + " ~ " + matcher.end(0) + " }");
			System.out.println("\t group(1) : " + matcher.group(1) 
				+ " { "  + matcher.start(1) + " ~ " + matcher.end(1) + " }");
			System.out.println("\t group(2) : " + matcher.group(2) 
				+ " { "  + matcher.start(2) + " ~ " + matcher.end(2) + " }");
			
		} // end while
		
		// 도우미 함수를 사용해보자
		System.out.println();
		regExpTest("My....", "-My1234-");
		regExpTest("(My)(....)", "-My1234-");
		regExpTest("My....", input);
		regExpTest("(My)(....)", input);
		regExpTest("ABC...DEF", input);
		
		System.out.println("프로그램 종료");
	} // end main
	
    
	// 도우미 함수
	public static void regExpTest(String regex, String input) {
		System.out.println("[정규표현식 매칭 테스트-------------------------]");
		System.out.println("정규표현식 : " + regex);
		System.out.println("입력문자열 : " + input);
		
		Matcher matcher = Pattern.compile(regex).matcher(input);
		int groupCount = matcher.groupCount();	// 그룹개수
		
		int matchCount = 0;
		while(matcher.find()) {
			matchCount++;	// 패턴 발견!
			System.out.println("    매치" + matchCount + " : " + matcher.group() 
				+ "{ " + matcher.start() + " ~ " + matcher.end() + " }");
			
			// 그룹이 있었다면 group별 출력
			if(groupCount > 0) {
				for(int i = 0; i <= groupCount; i++) {
					System.out.printf("\t group(%d) : %s { %d ~ %d }\n", 
						i, matcher.group(i), matcher.start(i), matcher.end(i));
				}
			}
		} // end while
		
		if(matchCount == 0) {System.out.println("    x매칭 없음x");}
		
		System.out.println();
	}
	
} // end class

 

3) com.lec.java.regexp03 패키지, RegExp03Main 클래스

package com.lec.java.regexp03;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* 정규표현식 에 사용하는 각종 표현식들
 *  정규표현식	설명
 *  ^	문자열 시작
 *  $	문자열 종료
 *  .	임의의 문자 [단 ‘'는 넣을 수 없습니다.]
 *  *	앞 문자가 0개 이상의 개수가 존재할 수 있습니다.
 *  +	앞 문자가 1개 이상의 개수가 존재할 수 있습니다.
 *  ?	앞 문자가 없거나 하나 있을 수 있습니다.
 * []	문자의 집합이나 범위를 표현합니다. -기호를 통해 범위를 나타낼 수 있습니다. ^가 존재하면 not을 나타냅니다.
 * {}	횟수 또는 범위를 나타냅니다.
 * ()	괄호안의 문자를 하나의 문자로 인식합니다. (그룹)
 * |	패턴을 OR 연산을 수행할 때 사용합니다.
 * \s	공백 문자
 * \S	공백 문자가 아닌 나머지 문자
 * \w	알파벳이나 숫자
 * \W	알파벳이나 숫자를 제외한 문자
 * \d	[0-9] 숫자
 * \D	숫자를 제외한 모든 문자
 * (?i)	대소문자를 구분하지 않습니다.
 * 
 * 
 * 자바 정규표현식에 사용되는 escaped character 들
 *    \.[]{}()<>*+-=!?^$|
 */
public class RegExp03Main {

	public static void main(String[] args) {
		System.out.println("정규표현식\n");

		String regex, intput, title;
		String [] arrInput;
		
		//─────────────────────────────────────────
		title = "^ : 바로 문자뒤의 문자열로 시작됨";
		regex = "^The";	// The 로 시작하는 문자열 패턴
		arrInput = new String[] {
				"The Things",		// 매치1: The {0~3}
				"On The Things",	// 매칭 없음
				" The THe The",		// 매칭 없음, 앞에 공백도 문자로 인식하기 때문에
				"The The the The"	// 매치1: The {0~3}
		};
		
		//─────────────────────────────────────────
		title = "$ : 문자열의 마지막이 이 문자열로 마무리 됨";
		regex = "Man$";	// Man 으로 끝나는 문자열 패턴
		arrInput = new String[] {
				"SuperMan",		// 매치1: Man {5~8}
				"AquaMan",		// 매치1: Man {4~7}
				"WonderWoman",	// 매칭 없음
				"WonderWoMan",	// 매치1: Man {8~11}
				"PostMan "		// 매칭 없음, 맨 끝에 있는 공백도 문자로 인식하기 때문에
		};
			
		//─────────────────────────────────────────
		title = "^표현식$ : 정확하게 전체패턴매칭되는 문자열";
		regex = "^Su...Man$";	// TODO
		arrInput = new String[] {
				"SuperMan",	
				"SugarMan",
				"Super Man",
				" SuperMan",
				"SuperMan"
		};
			
		//─────────────────────────────────────────
		title = " . : 어떤 문자든지 임의의 '한문자'를 말한다.꼭 하나의 문자와 매칭";
		regex = "x.y";	// TODO
		arrInput = new String[] {
				"xyz",
				"xxzdfdk",
				"aa10x9zbxbz",
				"xz",
				"90x zxx_zdf",  // 공백도 하나의 문자다! 매칭된다
				"xbz",				
				"xyyz x1y xyyy xxxyyyxxyyxyxyyyxyxyxyxyy"
		};
		
		//─────────────────────────────────────────
		title = " * : 바로 앞의 문자가 없거나 한개 이상의 경우를 매칭";
		regex = "ab*"; // b는 없어도 되고 한 개 이상 있어도 된다!
		arrInput = new String[] {
				"a",
				"abc",
				"ab",
				"abbbaaaabababbab",
				"bbba",
				"cdef"
		};
		
		//─────────────────────────────────────────
		title = " + : 바로 앞의 문자를 나타내면 꼭 한개 혹은 그 이상을 매칭";
		regex = "ab+"; // b는 반드시 한 개 이상 있어야 한다!
		arrInput = new String[] {
				"a",
				"abc",
				"ab",
				"abbbaaaabababbab",
				"bbba",
				"cdef"
		};
		
		//─────────────────────────────────────────
		title = " ? : 바로 앞의 문자가 한개 있거나 없는것을 매칭";
		regex = "ab?"; // b는 없거나 한 개만!!
		arrInput = new String[] {
				"a",
				"abc",
				"kkabcc",
				"abbbaaaabababbab",
				"bbba"
		};

		//─────────────────────────────────────────
		title = " [] : 안에 존재하는 문자들중 한 문자만을 매칭";
		regex = "[abc]"; // a 또는 b 또는 c 중의 한 문자에 매칭
		arrInput = new String[] {
				"able",
				"bible",
				"cable",
				"xenosys"	
		};
		regex = "[abc]+";
		regex = "[a-z]+";	// a ~ z 까지 문자 1개 이상
		
		arrInput = new String[] {
				"abc100",
				"abcDefGHIUJ-KLM123opQrstuz"	// 대소문자 구분함!
		};
		regex = "[a-zA-Z]+";
		regex = "[a-zA-Z0-9]+";
		regex = "[a-zA-Z0-9-]+";
		
		arrInput = new String[] {
				"23",
				"0",
				"-10",
				"012"
		};
		regex = "^[1-9][0-9]*$";	// 자연수 에 대한 정규표현식
		
		//─────────────────────────────────────────
		title = " {} : 앞에 있는 문자나 문자열의 등장개수를 정함";
		regex = "ab{2}"; // a로는 반드시 시작하고 b는 두 개가 매칭되는 것
		arrInput = new String[] {
				"abb",
				"abbb",
				"abbbabbbbbbbbabaabab"
		};
		regex = "ab{2,}";	// b의 개수가 2개 이상
		regex = "ab{3,5}";	// b의 개수가 3개부터 5개까지, 
		//regex = "ab{3, 5}";	// 오류 : {중괄호 안에는 띄어쓰기 하면 안됨}
					// java.util.regex.PatternSyntaxException
		
		//─────────────────────────────────────────
		title = " () : ()안에 있는 글자들을 그룹화 ";
		regex = "a(bc)*"; // (bc) 가 없거나 하나 이상
		arrInput = new String[] {
				"abc",
				"abcbcbbca",
				"abcabcabc"
		};

		//─────────────────────────────────────────
		title = " | : OR 연산자  역할";
		regex = "a|b"; // a 또는 b 둘 중 하나
		arrInput = new String[] {
				"a",
				"b",
				"ab",
				"xyz",
				"abccbbcccbbaaabcbccbbaacbaaaccbc"
		};
		regex = "(a|b)+";

		//─────────────────────────────────────────
		title = "(?i)  : 대소문자 구분안하고 매칭 ";  // 타 언어 정규표현식과 다름
		regex = "(?i)abc"; 
		arrInput = new String[] {
				"abc",
				"Abc",
				"ABC"
		};
		
		//─────────────────────────────────────────
		title = "\\s : 공백,  \\S : 공백아닌 문자";
		regex = "\\s+";	// 공백(스페이스바, 줄바꿈, 탭) 하나 이상
		arrInput = new String[] {
				"Hello My World",
				"He \tllo My World",
				"\n\t Hello My World\n\n"
		};
		regex = "\\S+";	// 공백 아닌 문자
		
		//─────────────────────────────────────────
		title = "\\w : 알파벳이나 숫자, \\W 알파벳이나 숫자를 제외한 문자";
		regex = "\\w+"; 
		arrInput = new String[] {
				"This is 2020-03-23 !!"
		};
		regex = "\\W+";
		
		//─────────────────────────────────────────
		title = "\\d : [0-9] 숫자, \\D 숫자를 제외한 모든 문자";
		regex = "\\d+"; 
		arrInput = new String[] {
				"This is 2020-03-23 !!"
		};
		regex = "\\D+";

		//─────────────────────────────────────────
		title = "escaped character 매칭 시키기";
		regex = ".+"; // TODO
		arrInput = new String[] {
				"My name is ..."
		};
		regex = "[.]+"; // TODO

		//*****************************************
		// 패턴매칭 수행
		System.out.println(title);
		regExpTest(regex, arrInput);

		System.out.println("프로그램 종료");
	} // end main()
	
	// 도우미 함수
	public static void regExpTest(String regex, String [] arrInput) {
		for(String input : arrInput) regExpTest(regex, input);
	}
	
	public static void regExpTest(String regex, String input) {
		System.out.println("[정규표현식 매칭 테스트]-----------------");
		System.out.println("정규표현식: " + regex);
		System.out.println("입력문자열: " + input);
		
		Matcher matcher = Pattern.compile(regex).matcher(input);
		int groupCount = matcher.groupCount();  // 그룹 개수
		
		int matchCount = 0;		
		while(matcher.find()) {
			matchCount++;
			System.out.println("    매치" + matchCount + ": " + matcher.group() 
				+ " {" + matcher.start() + "~" + matcher.end() + "}");
			
			// 그룹이 있으면 group별 출력
			if(groupCount > 0) {
				for(int i = 0; i <= groupCount; i++) {	 // i 범위 주목!	
					System.out.printf("\t group(%d): %s {%d~%d}\n",
							i, matcher.group(i), matcher.start(i), matcher.end(i));
				}
			}
			
		} // end while
		if(matchCount == 0) System.out.println("   Ⅹ매치 없슴Ⅹ");
		System.out.println();
	} // end regExpTest()

} // end class

 

 

5. Lec13_Class
1) com.lec.java.class01 패키지, Class01Main, MyTV 클래스

** Class01Main

package com.lec.java.class01;
/*
 	클래스 정의 및 사용
 	
 	우리가 만든 클래스를 사용하려면,
	그 클래스의 '인스턴스(실체 instance)'를 생성해야 함.
	
	구문
		클래스이름 변수이름 = new 생성자();
		생성자(): 클래스의 이름과 동일, 클래스의 멤버변수들을 초기화
		
 	new 로 생성하는 instance 들은
 	지역변수와는 달리 인스턴스가 생성될 때 (자동으로) 초기화가 된다.
 	특별히 초기화를 할 값들이 지정되어 있지 않을 때는
 	각 변수 타입의 기본값(디폴트 값)으로 초기화가 됨
 		boolean -> false, 숫자타입(int, double, ...) -> 0
 		String, 참조 타입(클래스) -> null
 	
 	지역변수: 메소드 안에서 선언된 변수
 	지역변수는 사용하기 전에 반드시 초기화를 해줘야 함.
 */
public class Class01Main {

	public static void main(String[] args) {
		System.out.println("클래스 생성 & 사용");
		
		MyTV tv1;
		tv1 = new MyTV();		// MyTV 인스턴스 생성!
		tv1.displayStatus();
		
		// TV 켜기
		tv1.powerOnOff();
		
		// 볼륨 조정
		tv1.volumeUp();
		tv1.volumeUp();

		// 채널 조정
		tv1.channelUp();
		tv1.channelUp();
		tv1.channelUp();
		
		// 일반적으로 
		// 멤버변수는 private 으로 설정하여
		// 외부클래스에서 아래와 같이
		// 직접 사용하는 것을 금지하게 설계함.
		// 현재 isPowerOn, volume, channel 멤버 변수는
		// private로 설정되어 있어서 외부클래스에서 값을 변경하지 못함.
//		tv1.isPowerOn = false;
//		tv1.volume = 32;
//		tv1.channel = 100;
		
		tv1.displayStatus();
		
		System.out.println();
		MyTV tv2 = new MyTV();		// 다른 MyTV 인스턴스
		tv2.powerOnOff();
		tv2.channelUp();
		tv2.volumeUp();
		tv2.displayStatus();
		
		System.out.println();
		System.out.println(tv1);	// 출력값: com.lec.java.class01.MyTV@15db9742
		System.out.println(tv2);	// 출력값: com.lec.java.class01.MyTV@6d06d69c
		
		System.out.println();
		tv1 = tv2;	// 어떻게 될까? 
				// 결과! tv2의 주소값이 tv1으로 복사됨(tv1과 tv2에 저장된 주소값은 동일해짐)
				// 원래 tv1이 레퍼런싱하던 인스턴스는 Garbage Collector에 의해 소멸된다. (GC된다)
				// 왜? 레퍼런싱이 끝기면 Garbage Collector가 자동으로 지우기 때문에
		tv1.displayStatus();
		tv1.powerOnOff();
		tv2.displayStatus();	// tv1과 tv2는 같은 인스턴스를 레퍼런싱 하고 있다!
		
		System.out.println(tv1); // 출력값: com.lec.java.class01.MyTV@6d06d69c
		System.out.println(tv2); // 출력값: com.lec.java.class01.MyTV@6d06d69c

		System.out.println("\n프로그램 종료");
	} // end main()
	
} // end class

 

** MyTV 

package com.lec.java.class01;
/*
	클래스:
		우리가 만들고자 하는 대상의 '상태' 와 '기능' 을 함께 가지고 있는 '데이터 타입'
	상태(속성, 필드) -> 클래스의 멤버변수로 정의 
	    field, attribute, member variable 라고 함
	기능(동작) -> 클래스의 멤버메소드로 정의  
	    behavior, member method 라고 함
	
	
	일반적으로 
	 멤버변수(필드)는 private 으로 설정. 
	 멤버메소드는 public 으로 설정.
*/
public class MyTV {
	// TV 의 상태 (속성) --> (멤버)변수
	// 멤버변수 : 같은 클래스에서 정의된 모든 메소드에서 사용 가능.
	private boolean isPowerOn;	// 전원 on/off
	private int channel;		// 현재 채널
	private int volume;		// 현재 볼륨
	
	
	// TV 의 기증 (동작) --> (멤버)메소드
	// 현재 상태 표시
	public void displayStatus() {
		System.out.println("TV 현재 상태");
		System.out.println("------------------------------");
		System.out.println("전원상태 : " + isPowerOn);	// 동일클래스 안의 멤버들 서로 사용 가능.
		System.out.println("채널상태 : " + channel);
		System.out.println("볼륨상태 : " + volume);
		System.out.println("------------------------------");
	} // end displayStatus()
	
	// 전원 토글 동작
	public void powerOnOff() {
		if(isPowerOn) {	// TV가 켜져 있다면
			isPowerOn = false;
			System.out.println("TV를 끕니다.");
		} else {	// TV가 껴져있다면
			isPowerOn = true;
			System.out.println("TV를 켭니다.");
		}
	} // end powerOnOff()
	
	// 채널+ 동작
	public int channelUp() {
		channel++;
		System.out.println("현재 채널 : " + channel);
		return channel;
	} // end channelUp()
	
	// 채널- 동작
	public int channelDown() {
		channel--;
		System.out.println("현재 채널 : " + channel);
		return channel;
	} // end channelDown()
	
	// 볼륨+ 동작
	public int volumeUp() {
		volume++;
		System.out.println("현재 볼륨 : " + volume);
		return volume;
	} // end volumeUp()
	
	// 볼륨- 동작
	public int volumeDown() {
		volume--;
		System.out.println("현재 볼륨 : " + volume);
		return volume;
	} // end volumeDown()

}

 

2) com.lec.java.class02 패키지, Class02Main, Circle, Rectancle 클래스

** Class02Main

package com.lec.java.class02;


public class Class02Main {

	public static void main(String[] args) {
		System.out.println("클래스 연습");		
		
		Circle c1 = new Circle();
		Circle c2 = new Circle(3.0);
		
		System.out.println();
		double perimeter = c1.calcPerimeter();
		System.out.println("c1의 둘레 : " + perimeter);

		perimeter  = c2.calcPerimeter();
		System.out.println("c2의 둘레 : " + perimeter);
		
		System.out.println();
		System.out.println("c1의 넓이 : " + c1.calcArea());
		System.out.println("c2의 넓이 : " + c2.calcArea());
		
		System.out.println();
		Rectancle r1 = new Rectancle();
		Rectancle r2 = new Rectancle(2, 3);
		
		// r1, r2 의 둘레, 넓이 출력
		perimeter = r1.calcPerimeter();
		System.out.println("사각형1의 둘레: " + perimeter);
		double area = r1.calcArea();
		System.out.println("사각형1의 넓이: " + area);
		
		perimeter = r2.calcPerimeter();
		System.out.println("사각형2의 둘레: " + perimeter);
		area = r2.calcArea();
		System.out.println("사각형2의 넓이: " + area);
				
		System.out.println("\n프로그램 종료");
	} // end main()

} // end class Class02Main

 

** Circle

package com.lec.java.class02;
/* 생성자(Constructor)
 * 	생성자의 목적: 인스턴스 생성시 멤버변수들의 초기화
 * 	생성자의 이름은 반드시 클래스의 이름과 동일
 * 	생성자는 리턴 타입이 없다.
 * 	생성자도 매개변수(argument)를 가질 수 있습니다.
 * 	생성자도 오버로딩(overload) 가능
 * 
 * 	클래스를 만들 때, 생성자를 따로 만들지 않으면
 * 	'디폴트 생성자(default constructor)'를 자동으로 만들어줌.
 * 	디폴트 생성자란 : 매개변수가 없는 생성자.  모든 멤버변수는 기본값으로 초기화
 * 	(주의) 클래스에서 하나 이상의 생성자를 만들게 되면,
 * 	           자동으로 디폴트 생성자를 만들어 주지 않습니다.
 * 	(강력권장) 아무일도 안하더라도 디폴트 생성자는 반드시 만들어 주자. 
 */
public class Circle {

	// 원의 상태(속성) --> 멤버변수
	public double radius;	// 반지름
	
    
	// 생성자(Constructor) (들...)
	// 생성자의 목적: 인스턴스 생성시 멤버변수들의 초기화
	// 디폴트 생성자(default constructor) : 매개변수가 없는 생성자 
	public Circle() {	
		System.out.println("Circle() 생성자 호출");
		System.out.println("반지름 : " + radius);
	}
	
	// 생성자는 오버로딩 가능
	public Circle(double r) {
		System.out.println("Circle(" + r + ") 생성자 호출");
		radius = r;	// 멤버변수 초기화
		System.out.println("반지름 : " + radius);
	}
	
    
	// 원의 기능(동작) --> 멤버메소드
	// 윈의 둘레 계산
	public double calcPerimeter() {
		return 2 * Math.PI * radius;
	}
	
	// 원의 면적 계산
	public double calcArea() {
		return Math.PI * radius * radius;
	}
    
}

 

** Rectancle

package com.lec.java.class02;

public class Rectancle {
	
	// 속성 : 멤버변수
	// 가로, 세로
	double width;
	double height;
	
	
	// 생성자 : 인스턴스 생성시 멤버변수들의 초기화
	// 1. 디폴트 생성자 : 매개변수가 없는 생성자
	public Rectancle() {
		System.out.println("Rectangle() 생성");
		width = 100;	// 디폴트 값 지정 가능
		height = 100;
		System.out.println("가로 : " + width);
		System.out.println("세로 : " + height);
	}
	
	// 2. 매개변수 가진 생성자
	public Rectancle(double w, double h) {
		System.out.println("Rectangle(w, h) 생성");
		width = w;	// 멤버 변수 초기화
		height = h;
		System.out.println("가로 : " + width);
		System.out.println("세로 : " + height);
	}

	
	//동작 : 멤버 메소드
	// 1) calcPerimeter : 사각형의 둘레
	public double calcPerimeter() {
		return (height + width) * 2;
	}
	
	// 2) calcArea : 사각형의 넓이
	public double calcArea() {
		return height * width;
	}
	
}

 

[추가] 직접 생성자를 선언하지 않으면 컴파일러가 기본 생성자를 생성하지만
         프로그래머가 생성자를 선언하는 순간 컴파일러는 기본생성자를 선언하지 않는다.
         꼭! 기본생성자를 선언하는 습관을 들이자...!!

[추가] 프로그래머는 생성자를 직접 만들 수 있음(오버로딩을 통해, 매개변수만 다르게)
         생성자도 메서드와 동일하게 선언되어 있지 않으면 오류 발생!

3) com.lec.java.class03 패키지, Class03Main, Number, Numeric 클래스

** Class03Main

package com.lec.java.class03;
/*
	캡슐화, 은닉, 추상화

	클래스 안에 필요한 '속성' 과 '행동' 을 멤버로 묶고
	외부에서의 '직접적인 접근을 제한'하여
	객체의 데이터 와 메소드를 은닉(hiding)하고, 
	사용자에게는 필요한 기능만 제공하여 추상화(abstraction) 하는   
	객체지향 기술을 '캡슐화(encapsulation)' 라고 한다
	
	
	클래스의 멤버변수를 접근하기 위한 기능을 제공하는 메소드를 
	getter , setter 라 한다
*/
public class Class03Main {

	public static void main(String[] args) {
		System.out.println("Getter & Setter");
		
		Number n1 = new Number(100, 'A');
		//n1.num = 200;		// not visible : 데이터 은닉
		//n1.name = 400;	// 이름 없음, 존재하지 않음
					// name cannot be resolved or is not a field
		
		System.out.println(n1.getNum());
		n1.setNum(200);
		System.out.println(n1.getNum());
		n1.setNum(-2);	// if 조건에 의해 값이 바뀌지 않음
		System.out.println(n1.getNum());
		
		System.out.println("프로그램 종료");
	} // end main()
    
} // end class Class03Main


** Number

package com.lec.java.class03;

public class Number {
	// 멤버변수
	private int num;
	private char ch;
	
	
	// 생성자
	// 1) 디폴트 생성자
	public Number() {}
	
	// 2) 매개변수 있는 생성자
	public Number(int num, char ch) {
		// 이제부터 num은 지역변수 num
		// 즉, 생성자를 통해 입력받은 매개변수 num이란 소리!
		// 그렇기 때문에 멤버변수 num에게 접근하려면 this를 이용!
		this.num = num;	// this : 자기 자신(인스턴스)를 가리킴
		this.ch = ch;
	}
	
	
	// 메소드
	// getter: 멤버 변수의 값을 리턴해 주는 메소드
	// setter: 멤버 변수의 값을 변경해 줄 수 있는 메소드
	
	// 일반적인 작명 관례
	// get변수이름()
	// set변수이름()
	// Camel notation 적용
	
	// 1) 멤버변수 Num의 getter, setter
	public int getNum() {
		return this.num;
	}
	
	public void setNum(int num) {
		if(num >= 0) {
			this.num = num;
		}
	}

	// 2) 멤버변수 ch의 getter, setter
	public int getCh() {
		return this.ch;
	}
	
	public void setCh(char ch) {
		this.ch = ch;
	}

}

 

** Numeric

package com.lec.java.class03;

public class Numeric {
	// 멤버변수
	private char ch;
	private byte operator;
	private int operand1;
	private int operand2;
	
	// 1) 기본생성자
	public Numeric() {}
	
	// 2) 매개변수 있는 생성자 [단축키] : Alt + Shift + S + O
	public Numeric(char ch, byte operator, int operand1, int operand2) {
		super();
		this.ch = ch;
		this.operator = operator;
		this.operand1 = operand1;
		this.operand2 = operand2;
	}


	// getter, setter : [단축키] Alt + Shift + S + R
	public char getCh() {
		return ch;
	}

	public void setCh(char ch) {
		this.ch = ch;
	}

	public byte getOperator() {
		return operator;
	}

	public void setOperator(byte operator) {
		this.operator = operator;
	}

	public int getOperand1() {
		return operand1;
	}

	public void setOperand1(int operand1) {
		this.operand1 = operand1;
	}

	public int getOperand2() {
		return operand2;
	}

	public void setOperand2(int operand2) {
		this.operand2 = operand2;
	}
		
}

 

[추가] private로 선언된 멤버변수는 본인 클래스 이외의 다른 클래스에서 접근 불가능하다..!!
         접근하고 싶으면 getter, setter를 이용

4) com.lec.java.class04 패키지, Class04Main, Number 클래스

** Class04Main

package com.lec.java.class04;
/*
   클래스 안에서 this : 
	객체 내에서 자기자신(인스턴스)을 가리킴

   메소드 체이닝 (method chaining)
 	자기자신을 리턴하여, 연이어 메소드
 	호출 가능케 하는 메소드 설계
 	보통 setter 와 이와 같은 동작을 수행하는 메소드들에 적용하면 좋다
*/
public class Class04Main {

	public static void main(String[] args) {
		System.out.println("this & 메소드 체이닝");
		
		Number n1 = new Number();
		System.out.println("n1.num = " + n1.getNum());
		
		Number n2 = new Number(123);
		n1.add(n2);					// n1.num = 223
		System.out.println("n1.num = " + n1.getNum());
		
		Number n3 = new Number(10);
		n1.sub(n3);					// n1.num = 213
		System.out.println("n1.num = " + n1.getNum());
		
		n1.sub(new Number(100));	// n1.num = 113
		System.out.println("n1.num = " + n1.getNum());
		
		System.out.println();
		n1.setNum(100);
		
		// 위의 코드를 한 줄로 요약할 수 있음...!!
		// 이런 것을  메소드 체이닝 (method chaining)이라고 함
	 	// 그게 뭔데? 자기 자신을 리턴하여, 연이어 메소드
	 	//          호출 가능케 하는 메소드 설계
		n1.add(n2).sub(n3).sub(new Number(100));
		System.out.println("n1.num = " + n1.getNum());
		
		System.out.println();
		Number n4 = new Number();
		
		n4.setNum1(10);
		n4.setNum2(20);
		n4.setNum3(30);
		n4.setNum4(40);
		n4.setNum5(50);
		n4.setNum6(60);
		
		// 메소드 체이닝
		// 위의 코드를 아래와 코드처럼 한 줄로 작성 가능
		n4.setNum1(10).setNum2(20).setNum3(30).setNum4(40)
			.setNum5(50).setNum6(60);
		
		System.out.println("프로그램 종료");
	} // end main()

} // end class Class04Main


** Number 

package com.lec.java.class04;

public class Number {
	private int num = 100;	// 멤버 변수 선언시 초기값 명시 가능.
	
	
	// 1) 디폴트 생성자
	public Number() {}

	// 2) 매개변수 받는 생성자
	public Number(int num) {
		super();
		this.num = num;
	}

	
	// getter, setter
	public int getNum() {
		return this.num;	// return num;
	}
	public void setNum(int x) {
		this.num = x;
	}
	

	// 멤버 메소드
	public Number add(Number x) {
		this.num += x.num;
		return this;	// 자기 자신을 리턴
	}
	
	public Number sub(Number x) {
		this.num -= x.num;
		return this;	// 자기 자신을 리턴
	}
	
	
	// set 해야 할 멤버변수가 많~~은 경우
	// setter 들을 메소들 체이닝으로 관리하면 편리함
	private int num1;
	private int num2;
	private int num3;
	private int num4;
	private int num5;
	private int num6;

	public Number setNum1(int num1) {
		this.num1 = num1;
		return this;
	}

	public Number setNum2(int num2) {
		this.num2 = num2;
		return this;
	}

	public Number setNum3(int num3) {
		this.num3 = num3;
		return this;
	}

	public Number setNum4(int num4) {
		this.num4 = num4;
		return this;
	}

	public Number setNum5(int num5) {
		this.num5 = num5;
		return this;
	}

	public Number setNum6(int num6) {
		this.num6 = num6;
		return this;
	}
	
}

 

5) com.lec.java.class05 패키지, Class05Main, Point 클래스

** Class05Main

package com.lec.java.class05;
/* 메소드 체이닝 : method chaining
 *  	this는 자기자신 인스턴스 입니다.
 *  	메소드에서 this를 return 하면
 *  	호출한쪽에서 곧바로 연이어 호출 가능
 *  
 *   	객체.메소드1().메소드2().메소드2()....
 *   
 *  메소드체이닝을 사용하면, 반복되는 지루한 코딩을 줄여줄수 있다.
 *  프로그래밍시 각 메소드가 무엇을 리턴하는지는 항상 예의주시해야 합니다
 */
public class Class05Main {

	public static void main(String[] args) {
		System.out.println("클래스 정의 연습 : this, 메소드 체이닝");
		
		Point p1 = new Point();
		Point p2 = new Point(1.0, 2.0);
		
		double distance = p1.distance(p2);
		System.out.println("p1 ~ p2 사이의 거리 : " + distance);

		distance = p2.distance(p1);
		System.out.println("p2 ~ p1 사이의 거리 : " + distance);
		
		p1.add(p2).add(p2);
		System.out.println("p2 : " + p1.xPos + ", " + p1.yPos);
		
		System.out.println("프로그램 종료");
	} // end main()

} // end class Class05Main

 

** Point

package com.lec.java.class05;

public class Point {
	// 멤버 변수:
	//   1) double 타입의 xPos 선언, private
	//   2) double 타입의 yPos 선언, private
	double xPos;
	double yPos;

	
	// 생성자: 멤버 변수 초기화
	//   1) 디폴트 생성자
	public Point() {}

	//   2) Point(xPos, yPos)
	public Point(double xPos, double yPos) {
		super();
		this.xPos = xPos;
		this.yPos = yPos;
	}

	
	// 메소드
	// 멤버변수 xPos의 값을 전달받은 매개변수(x)의 값으로 변경하는 메소드
	public void setxPos(double xPos) {
		this.xPos = xPos;
	}
	
	// 멤버변수 yPos의 값을 전달받은 매개변수(y)의 값으로 변경하는 메소드
	public void setyPos(double yPos) {
		this.yPos = yPos;
	}
	
	
	
	// 메소드 이름: distance
	// 리턴 타입: double
	// 매개변수: Point
	// 기능: 자기위치에서 매개변수로 전달받은 점까지의 거리를 계산해서 리턴
	public double distance(Point pt) {
		double dist = Math.sqrt((xPos - pt.xPos) * (xPos - pt.xPos) 
				+ (yPos - pt.yPos) * (yPos - pt.yPos));
		
		return dist;
	}
	
	// 메소드 이름: add
	// 리턴 타입: Point
	// 매개변수: Point
	// 기능: 두 점(자기자신, 매개변수로 받은 점)에서
	//    x좌표는 x좌표끼리, y좌표는 y좌표끼기 더하기
	public Point add(Point pt) {
		xPos += pt.xPos;
		yPos += pt.yPos;
		return this;
	}
	
}


6) com.lec.java.class06 패키지, Class06Main, Score 클래스

** Class06Main

package com.lec.java.class06;

public class Class06Main {

	public static void main(String[] args) {
		System.out.println("클래스 연습 : 성적처리");
		
		Score score1 = new Score();
		score1.displayInfo();
		
		
		System.out.println();
		Score score2 = new Score("김남승", 80, 41, 91);
		score2.displayInfo();

		int total = score2.calcTotal();
		double avg = score2.calcAvg();
		System.out.println("총점: " + total);
		System.out.println("평균: " + avg);

		System.out.println("프로그램 종료");
	} // end main()

} // end class Clas06Main

 

** Score

package com.lec.java.class06;

public class Score {
	// 멤버변수 : 
	// 	학생 이름 String
	// 	국어점수 int 
	// 	수학점수 int
	// 	영어점수 int
	String name;
	int kor;
	int math;
	int eng;
	
	
	// 생성자: 멤버 변수 초기화
	//   1) 디폴트 생성자
	public Score() {}

	//   2) 매개변수 받는 생성자 (이름, 국어점수, 수학점수, 영어점수)
	public Score(String name, int kor, int math, int eng) {
		super();
		this.name = name;
		this.kor = kor;
		this.math = math;
		this.eng = eng;
	}

	
	// 메소드
	// 총점계산 메소드
	// 메소드이름 :calcTotal()
	// 리턴타입 : int
	public int calcTotal() {
		int total = 0;
		total = kor + eng + math;
		
		return total;
	} // end calcTotal()
	
	// 평균계산 메소드
	// 메소드 이름 : calcAvg()
	// 리턴타입 : double
	public double calcAvg() {
		double avg = 0;
		avg = (double)calcTotal() / 3;
		
		return avg;
	} // end calcAvg()
	
	// 메소드
	// 이름: displayInfo()
	// 리턴: void
	// 매개변수: none
	//   학생의 이름, 국어, 영어, 수학 점수 출력
	public void displayInfo() {
		System.out.print(name + " : ");
		System.out.print(kor + " : ");
		System.out.print(eng + " : ");
		System.out.print(math + " : ");
		System.out.println();
	} // end displayInfo()
	
}

'웹_프론트_백엔드 > JAVA프레임윅기반_풀스택' 카테고리의 다른 글

2020.03.25  (0) 2020.03.25
2020.03.24  (0) 2020.03.24
2020.03.20  (0) 2020.03.20
2020.03.19  (0) 2020.03.19
2020.03.18  (0) 2020.03.18