** 예제 1204 (Vector) **

package etc;

import java.util.Vector;

public class MySample1204 {

	public static void main(String[] args) {
		// 벡터
		Vector v = new Vector(5);
		v.add("1");
		v.add("2");
		v.add("3");
		print(v);
		
		//빈 공간 없애기.(용량과 크기가 같게)
		v.trimToSize();
		System.out.println("v.trimToSize()...");
		print(v);
		
		//벡터 용량 증가
		v.ensureCapacity(6);
		System.out.println("v.ensureCapacity...");
		print(v);
		
		v.setSize(7);	//총 7개 중 3개가 이미 값이 있으므로 4개는 null로 채움
		System.out.println("v.setSize()...");
		print(v);		//6개를 다사용해서 2배로늘어난다. -> capacity : 12
		
		//벡터의 data만 삭제됨. 기존 벡터의 size는 유지.
		v.clear();
		System.out.println("v.clear()...");
		print(v);
	}

	public static void print(Vector v) {
		System.out.println(v);
		System.out.println("size : " + v.size());
		System.out.println("capacity : " + v.capacity());		
	}
}



** Stack / Queue **

- 스택은 마지막에 저장한 데이터를 가장먼저 꺼내게 되는  LIFO(Last In First Out)

- 큐는 처음에 저장한 데이터를 가장 먼저 꺼내게 되는 FIFO(First In First Out)

- 큐는 인터페이스 -> 큐를 상속받은 LinkedList클래스

Stack 메소드 설 명
boolea empty() Stack이 비어 있는지 알려줌
Object peek() Stack 의 맨 위에 저장된 객체 반환  //다음주소값이 null이면 가장 위에있는 객체
Object pop() 맨 위에 저장된 객체를 꺼낸다.
Object push(Object item) Stack 에 객체를 저장
int search(Object o) 주어진 객체를 찾아 위치를 반환, 실패시 -1반환(위치는 1부터 시작)

 

Queue 메소드 설 명
boolean add(Object o) Queue에 추가 (성공하면 true)반환
Object remove() Queue 에서 객체를 꺼내 반환
Object element() 삭제없이 요소를 읽어옴
boolean offer(Object o) 객체를 저장. 성공하면  true
Object poll() 객체를 꺼내서 반환 (비어있으면 null반환)
Object peek() 삭제없이 욧를 읽어옴 (비어있으면 null반환)

 

 

** LinkedList 생성자와 메소드 **

생성자 또는 메소드 설 명
LinkedList(); LinkedList 객체생성
boolean add(Object) 지정된 객체를 LinkedList끝에 추가, 성공 true 실패false
void add(int index, Object element) 지정된 위치에 객체 추가
boolean addAll(int index, Collection c) 지정된 위치에 주어진 컬렉션에 포함된 모든 요소를추가, 성공 true 실패false
boolean contains(Object o) 지정된 객체가 LinkedList에 포함되었는지 알려줌
boolean containsAll(Collection o) 지정된 컬렉션의 모든 요소가 포함되었는지 알려줌
Object get(int index) 지정된 위치의 객체를 반환
boolean isEmpty() LinkedList가 비어 있는지 알려줌. 비어있으면 true
boolean remove (Object o) 지정된 객체 제거, 성공 true 실패false
int size() LinkedList에 저장된 객체 수 반환
boolean retainAll(Collection c) 지정된 컬렉션의 모든 요소가 포함되어 있는지 확인
Object set(int index, Object element) 지정된 위치에 객체를 주어진 객체로 바꿈

 


** 예제 MySample1204_2 **

package etc;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class MySample1204_2 {

	public static void main(String[] args) {
		// Stack / Queue
		Stack st = new Stack();
		Queue  q = new LinkedList();		//Queue인터페이스의 구혀네인 LinkedList사용
		
		st.push("0");
		st.push("1");
		st.push("2");
		
		q.offer("3");
		q.offer("4");
		q.offer("5");
		
		System.out.println("Stack()------------");
		while(!st.empty()) {
			System.out.println(st.pop());
		}
		
		System.out.println("Queue()------------");
		while(!q.isEmpty()) {
			System.out.println(q.poll());
		}
	}
}

** 예제 MySample1204_3 **

package etc;

import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;

public class MySample1204_3 {

	public static void main(String[] args) {
		// ArrayList 와 LinkedList비교 (시간)
		ArrayList a = new ArrayList(2000000);
		LinkedList t = new LinkedList();
		
		System.out.println("순차적으로 추가...");
		System.out.println("ArrayList : " + add1(a));
		System.out.println("LinkedList : " + add1(t) + "\n");
		
		System.out.println("중간에 추가...");
		System.out.println("ArrayList : " + add2(a));
		System.out.println("LinkedList : " + add2(t) + "\n");
		
		System.out.println("중간 삭제...");
		System.out.println("ArrayList : " + remove2(a));
		System.out.println("LinkedList : " + remove2(t) + "\n");
		
		System.out.println("순차적으로 삭제...");
		System.out.println("ArrayList : " + remove1(a));
		System.out.println("LinkedList : " + remove1(t) + "\n");
	}
	
	//순차적으로 추가 
	public static long add1(List list) {			//모든클래스의 부모인 List로 매개변수 받음
		long start = System.currentTimeMillis();	//현재 시간을 밀리세컨드단위
		
		for(int i = 0 ; i < 1000000 ; i++) {
			list.add(i + "");
		}
		
		long end = System.currentTimeMillis();
		return end - start;
	}
	
	//중간에 추가
	public static long add2(List list) {
		long start = System.currentTimeMillis();
		
		for(int i = 0 ; i < 1000 ; i++) {
			list.add(500, "X");
		}
		
		long end = System.currentTimeMillis();
		return end - start;
	}
	
	//순차적으로 삭제
	public static long remove1(List list) {
		long start = System.currentTimeMillis();
		
		for(int i = list.size()-1 ; i >= 0 ; i --) {
			list.remove(i);
		}
		
		long end = System.currentTimeMillis();
		return end - start;
	}
	
	//중간 삭제
	public static long remove2(List list) {
		long start = System.currentTimeMillis();
		
		for(int i = 0 ; i < 10000 ; i++) {
			list.remove(i);
		}
		
		long end = System.currentTimeMillis();
		return end - start;
		
	}	
}

 

결론 :  순차적으로 추가/삭제하는 것은 ArrayList가 LinkedList 보다 빠르다.

결론 : 중간 데이터를 추가/삭제하는 것은 LinkedList가 ArrayList보다 빠르다.

 


** 예제 MySample1204_4 **

package etc;

import java.io.File;
import java.io.IOException;

public class MySample1204_4 {

	public static void main(String[] args) throws IOException {
		// File 클래스
		
		//절대경로와 상대경로
		File directory = new File("./tmep");		//상대경로 (./temp -> 상대경로의미) | ./ -> 현재디렉토리(.) 아래에있는(/) temp 라는 의미.
		//File directory = new File("C:\\project\\JAVA\\MyProject\\temp");	//절대경로(풀경로를 다적어준다.)
		directory.mkdir();		//디렉토리 생성
		
		//temp디렉토리에 temp_file.txt 파일 생성
		File file = new File(directory, "temp_file.txt");	//아직 파일이 만들어지지 않음.
		file.createNewFile();
		
		//생성file 객체가 디렉토리인지 파일인지 확인
		if(directory.isDirectory()) {
			System.out.println(directory.getName() + "은 디렉토리 입니다.");
		}
		
		if(file.isFile()) {
			System.out.println(file.getName() + "은 파일입니다.");
			System.out.println("파일 경로 : " + file.getPath());
			System.out.println("파일 크기 : " + file.length() + "(bytes)");
			
			System.out.println("쓰기 가능 여부 : " + file.canWrite());
			System.out.println("읽기 가능 여부 : " + file.canRead());
		}
		
		//파일 삭제
		if(file.delete()) {
			System.out.println(file.getName() + "이 삭제되었습니다.");
			
		}
		
		//디렉토리 삭제
		if(directory.delete()){
			System.out.println(directory.getName() + "디렉토리가 삭제되었습니다.");
		}
	}
}

** 예제 MySample1204_5 **

package etc;

import java.io.File;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;

public class MySample1204_5 {

	public static void main(String[] args) throws IOException {
//		// File객체를 이용하여 Scanner생성
//		File file = new File("./temp/source_data.txt");
//		
//		Scanner scn = new Scanner(file);
//		
//		//파일의 내용을 라인 단위로 출력
//		System.out.println(file.getName() + "파일의 데이터 내용.");
//		
//		while(scn.hasNextLine()) {
//			System.out.println(scn.nextLine());
//		}
//		
//		scn.close();	//->파일은 사용하고나면 닫아줘야한다.
		
		
//		//BufferedReader 이용
//		File file = new File("./temp/source_data.txt");
//		FileReader reader = new FileReader(file);
//		BufferedReader buffReader = new BufferedReader(reader);
//		
//		//파일 내용을 라인 단위로 출력
//		System.out.println(file.getName() + "파일 데이터 내용.");
//		String data = null;
//		
//		while((data = buffReader.readLine()) != null) {
//			System.out.println(data.toString());
//		}
//		
//		//입력스트림 종료
//		reader.close();
//		buffReader.close();
		
		
		String filePath = "./temp/source_data.txt";
		
		File file = new File(filePath);
		if(!file.exists()) {		//파일의 존재하는지 확인 후 해당파일이 없는경우 파일생성
			file.createNewFile();	//신규생성
		}
		
		//BufferedWriter 생성
		BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
		
		//파일에 쓰기
		writer.newLine();
		writer.write("앗 월요일이다.");
		writer.newLine();
		writer.write("즐거운 점심시간입니다.");
		writer.newLine();
		
		//버퍼 및 스트림 정리
		writer.flush();		//버퍼에 남은 데이터를 모두 쓰기
		writer.close();		//스트림 종료
	}
}

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

** 예제 etc pakage  MySample1201 **

package etc;

public class MySample1201 {
	
	final static int RECORD_NUM = 10;
	final static String TABLE_NAME = "회원정보";
	final static String[] CODE1 = {"010", "011", "017" ,"018", "019"};
	final static String[] CODE2 = {"남자","여자"};
	final static String[] CODE3 = {"10대","20대","30대","40대","50대"};

	public static void main(String[] args) {
		int i;
		
		for(i = 0 ; i < RECORD_NUM ; i++) {
			//INSERT INTO 회원정보 VALUES ('017', '여자', '20대', 101);
			System.out.println("INSERT INTO 회원정보 VALUES (" + 
											"'"    + getRandArr(CODE1) + 
											"', '" + getRandArr(CODE2) +
											"', '" + getRandArr(CODE3) +
											"', "  + getRand(100, 200) + ");");	//100~200사이 값 랜덤
		}
	}
	
	public static String getRandArr(String[] arr) {
		return arr[getRand(arr.length-1)];		//배열에 저장된 값 중 하나를 반환하는 용도.
	}
	
	public static int getRand(int n) {
		return getRand(0,n);
	}
	
	public static int getRand(int from, int to) {
		System.out.println("form : " + from + ", to : " + to);
		System.out.println("abs : " + (Math.abs(to-from)+1) + ", min : " + Math.min(from, to));
		
		return (int)(Math.random()*(Math.abs(to-from)+1)) + Math.min(from, to);
	}
}

** 예제 etc pakage  MySample1201_2 (SimpleDateFormat) **

package etc;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MySample1201_2 {

	public static void main(String[] args) {
		// SimpleDateFormat (날짜 데이터를 원하는 형태로 다양하게 출력)
		Date today = new Date();
		
		SimpleDateFormat s1, s2, s3, s4;
		SimpleDateFormat s5, s6, s7, s8, s9;
		
		s1 = new SimpleDateFormat("yyyy-MM-dd");
		s2 = new SimpleDateFormat("yy년 MMM dd일 E요일");
		s3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
		s4 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
		s5 = new SimpleDateFormat("오늘은 올해의 D번째 날입니다.");
		s6 = new SimpleDateFormat("오늘은 이달의 d번째 날입니다.");
		s7 = new SimpleDateFormat("오늘은 올해의 w번째 주입니다.");
		s8 = new SimpleDateFormat("오늘은 이달의 W번째 주입니다.");
		s9 = new SimpleDateFormat("오늘은 이달의 F번째 E요일 입니다.");
		
		System.out.println(s1.format(today));
		System.out.println(s2.format(today));
		System.out.println(s3.format(today));
		System.out.println(s4.format(today));
		System.out.println(s5.format(today));
		System.out.println(s6.format(today));
		System.out.println(s7.format(today));
		System.out.println(s8.format(today));
		System.out.println(s9.format(today));
		
		/*
		 * y : 년 | M : 월 | d : 일 | E : 요일 | a : 오전/오후
		 * H : 시간 | m : 분 | s : 초 
		 */
		
		String patternKorea = "yyyy-MM-dd";
		String patternUSA = "MM-dd-yyyy";
		String patternUK = "dd-MM-yyyy";
		String pattern1 = "E요일 HH시 mm분 ss초";
		
		SimpleDateFormat p1 = new SimpleDateFormat(patternKorea);
		SimpleDateFormat p2 = new SimpleDateFormat(patternUSA);
		SimpleDateFormat p3 = new SimpleDateFormat(patternUK);
		SimpleDateFormat p4 = new SimpleDateFormat(pattern1);
		
		System.out.println("현재 날짜 : " + today);
		System.out.println("한국형(년월일) : " + p1.format(today));
		System.out.println("미국형(년월일) : " + p2.format(today));
		System.out.println("영국형(년월일) : " + p3.format(today));
		System.out.println("1형(년월일) : " + p4.format(today));
	}
}

 

실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 




** 컬렉션 프레임웍 (Collections Framework) **

데이터를 저장하는 클래스들을 표준화 설계한 것

데이터를 다루고 표현하기 위한 단일화된 구조

 

* 컬렉션 프레임웍의 핵심 인터페이스

인터페이스 특징
List   순서가 있는 데이터의 집합, 데이터의 중복을 허용
  구현클래스 : ArrayList, LinkedList, Stack, Vector 등
Set   순서를 유지하니 않는 데이터의 집합, 데이터의 중복을 허용하지 않음
  구현클래스 : HashSet, TreeSet
Map   키(key)와 값의 쌍으로 이루어진 데이터들의 집함
  순서는 유지되지 않으며, 키는 중복을 허용하지 않고, 값은 중복을 허용
  구현클래스 : HashMap, TreeMap, Hashtable, Properties

 

- 키란(key) ?

- 데이터 집합 중에서 어떤 값(value)을 찾는데 열쇠 (key) 가 됨으로 키 (key) 는 중복을 허용하지 않음

 

** List **

배열과 비슷하지만 배열보다 편리한 기능을 많이 가지고 있음.

배열의 경우 크기를 한번 지정하면 사이즈가 고정이되어 변경할 수  없지만 

리스트의 경우 자료를 넣는 많큼 자동적으로 사이즈가 늘어나기 때문에 동적으로 활용하기에 유리함.

 

* 대표 함수

함수 설명
add    List 에 자료를 넣을 때 사용하는 함수
   예) ArrayList<String>list = new ArrayList<String>();       //<>는 타입 넣어줌
         list.add("사과")
         list.add( 1, "바나나" )        //숫자에 해당하는 곳에 바나나자료 넣어준다.
get    List의 데이터를 가져올 때 사용.  
   예) list.get(1)
size    List의 길이를 리턴하는 함수
   예) list.size()
contains    List에 해당값이 있느면 true, 없으면 false를 리턴.
   예) list.contains("사과")
remove    List에서 삭제가 성공하면 true, 실패하면 false 리턴.
   예) list.remove("사과")  / 
         list.remove(0)          //0번째 인덱스에 있는 값 삭제

 

* Colletion 인터페이스에 정의된 메서드

.

.

.....

 

 

 

 

 

 

** ArrayList **

컬렉션 프레임웍에서 가장 많이 사용되는 컬렉션 클래스

특징 - List 인터페이스르르 구현하기 떄문에 데이터의 저장순서가 유지되고 중복을 허용함

Object 배열을 애용해서 데이터를 순차적으로 저장

배열에 순서대로 저장되며, 배열에 더 이상 저장할 공간이 없으면 보다 큰 새로운 배열을 생성해서 기존의 배열 내용을 새로운 배열로 복사한 다음에 저장

 

* ArrayList의 생성자와 메서드

메소드 설명
ArrayList() 크기가 10인 ArrayList생성
boolean add(Object o) ArrayList의 마지막에 객체 추가 , 성공 true
void add (int index, Object element) 지정된 위치에 객체 저장
boolean contains(Object o) 지정된 객체가 ArrayList에 포함되어 있는지 확인
Object get(int index) 지정된위치에 저장된 객체 반환
Object remove(int index) 지정된 위치에 있는 객체 제거
boolean retainAll(Collection c) ArrayList에 저장된 객체 중에서 주어진 컬렉션과 공통된 것들만을 남기고 나머지는 삭제

 

ArrayList 크기(길이)가 10인 ArrayList가 생겨도 값이 5개만 들어오면 크기가 5로 바뀜.

 


** 예제 etc pakage  MySample1201_3 (ArrayList) **

package exec;

import java.util.ArrayList;
import java.util.Collections;

public class MySample1201_3 {

	public static void main(String[] args) {
		// ArrayList
		ArrayList<String> list1 = new ArrayList<String>(10);
		list1.add("A");
		list1.add("B");
		list1.add("C");
		list1.add("D");
		
		System.out.print("list1 초기 상태 : ");
		System.out.println(list1 + " - size : " + list1.size());
		
		System.out.println("\n인덱스1에 B 추가");
		list1.add(1, "B");
		
		System.out.print("B추가 후 : ");
		System.out.println(list1 + " - size : " + list1.size());
		
		System.out.println("\n인덱스2의 값 삭제");
		list1.remove(2);
		
		System.out.print("인덱스2삭제 후 : ");
		System.out.println(list1 + " - size : " + list1.size());
		
		System.out.println("\n인덱스 2번째 위치 값 불러오기 : " + list1.get(2));
		
		System.out.println();
		
		ArrayList list2 = new ArrayList(10);	//타입<String>쓰지않으면, ArrayList에 객체를 넣을 수 있다.
		list2.add(new Integer(5));				//5를 넣지안고 Integer객체에 5를 넣은 이유
		list2.add(new Integer(4));
		list2.add(new Integer(2));
		list2.add(new Integer(0));
		list2.add(new Integer(1));
		list2.add(new Integer(3));
		
		System.out.println("list2 : " + list2);
		
		ArrayList list3 = new ArrayList(list2.subList(1, 4));	//인덱스 1번째부터 (4-1) 위치까지 가져오는 것
		System.out.println("list3 : " + list3); 
		print(list2, list3);
		
		Collections.sort(list2);		//<T> : 어떠한 데이터탑입도 다 받는다는 의미
		Collections.sort(list3);
		print(list2, list3);
		
		//list2에 list3 전체가 포함되어 있는지 확인(true.false)
		System.out.println("list2.containsAll(list3) - " + list2.containsAll(list3));
		System.out.println("list3.containsAll(list2) - " + list3.containsAll(list2));

	}
	
	static void print(ArrayList list1, ArrayList list2) {
		System.out.println("list1 : " + list1);
		System.out.println("list2 : " + list2);
		System.out.println();
	}
}

** 문제 etc pakage  MySample1201_4 (ArrayList) **

// ArrayList
/* 
 * 문제)5명의 사람이름을 입력받아서 ArrayList에 저장한 후에 '김'씨 성을 가진 사람을 모두 출력하는 프로그램.
 * 입력예)홍길동
 *  이둘리
 *  김길동
 *  김둘리
 *  최길동
 * 출력예)[김길동] [김둘리]
 *  김씨 성을 가진 분은 모두 2명입니다.
 * 단, 입력시 nextLine() 사용하며, '김'으로 시작한 것을 찾는 메서드는 get(i) 가져와서 startsWith("김")->true, false
 */

package exec;

import java.util.ArrayList;
import java.util.Scanner;

public class MySample1201_4 {

	public static void main(String[] args) {
		// ArrayList
		/* 
		 * 문제)5명의 사람이름을 입력받아서 ArrayList에 저장한 후에 '김'씨 성을 가진 사람을 모두 출력하는 프로그램.
		 * 입력예)홍길동
		 * 		이둘리
		 * 		김길동
		 * 		김둘리
		 * 		최길동
		 * 출력예)[김길동]	[김둘리]
		 * 		김씨 성을 가진 분은 모두 2명입니다.
		 * 단, 입력시 nextLine() 사용하며, '김'으로 시작한 것을 찾는 메서드는 get(i) 가져와서 startsWith("김")->true, false
		 */
		
		ArrayList<String> name = new ArrayList<String>(5);
		int cnt = 0;		//몇명인지 체크
		int i;
		
		Scanner scn = new Scanner(System.in);
		
		System.out.println("5명의 이름을 입력해 주세요.");
		
		for(i = 0 ; i < 5 ; i++	) {
			name.add(scn.nextLine());
			
		}
		
		String str;
		
		for(i = 0 ; i < name.size() ; i++) {
			
			str = name.get(i);			//str쓰지않고 name.get(i)를 직접 사용가능
			if(str.startsWith("김")) {
				cnt++;
				System.out.print("[" + name.get(i) + "]  ");
			}
		}
		
		System.out.println();
		System.out.println("김씨 성을 가진 분은 모두 " + cnt + "입니다.");
	}
}

** 문제 etc pakage  MySample1201_5 (ArrayList) **

package exec;

import java.util.ArrayList;
import java.util.Scanner;

public class MySample1201_5 {

	public static void main(String[] args) {
		// ArrayList 문제
		/*
		 * 문제)5명의 별명을 입력받아 ArrayList에 저장하고 이들 중 별명의 길이가 제일 긴 별명을 출력하는 프로그램
		 * 입력예)세일러문
		 * 		크루지
		 * 		놀부
		 * 		순대렐라
		 * 		달려라하니
		 * 출력예)가장 길이가 긴 별명은 > 달려라하니
		 * 단, 별명의 길이는 모두 다르게 입력함.
		 */
		
		Scanner scn = new Scanner(System.in);
		
		ArrayList<String> nick = new ArrayList<String>(5);
		
		int i, maxnickIndex = 0;
		int tmp = 0;
		System.out.println("5명의 이름을 입력하세요.");
		for(i = 0 ; i < 5 ; i++) {
			nick.add(scn.nextLine());
			
			if(nick.get(i).length() > tmp) {
				tmp = nick.get(i).length();
				maxnickIndex = i;
		}
		
//		for(i = 0 ; i < nick.size()	; i++)	{
//			if(nick.get(i).length() > tmp) {
//				tmp = nick.get(i).length();
//				maxnickIndex = i;
//			}
		}
		
		System.out.println("가장 길이가 긴 별명은 > " + nick.get(maxnickIndex));
		
		
//		//선생님 풀이
//		ArrayList<String> list = new ArrayList<String>();
//		int[] lengthArr = new int[5];
//		int max = lengthArr[0];
//		int i;
//		
//		for(i = 0 ; i < 5 ; i++) {
//			list.add(scn.nextLine());
//		}
//		
//		for(i = 0 ; i < 5 ; i++) {
//			lengthArr[i] = list.get(i).length();
//			
//			if(max < lengthArr[i]) {
//				max = lengthArr[i];
//			}
//		}
//		
//		for(i = 0 ; i < 5 ; i++) {
//			if(max == list.get(i).length()) {
//				System.out.println("가장 길이가 긴 별명은 > " + list.get(i));
//				break;
//			}
//		}
	}
}

** 문제 etc pakage  MySample1201_6 (ArrayList) **

package etc;

public class Student {

		private int grade;
		private int ban;
		private int num;
		private String name;
		private int korean;
		private int english;
		private int math;
		private int totalScore;
		private double avg;
		private int ranking;
		
		public Student() {
			this(0,0,0,"",0,0,0);
		}
		
		public Student(int grade, int ban, int num, String name, int korean, int english, int math) {
			setGrade(grade);
			setBan(ban);
			setNum(num);
			setName(name);
			setKorean(korean);
			setEnglish(english);
			setMath(math);
			setTotalScore(getKorean() + getEnglish() + getMath());
			setAvg((double)getTotalScore() / 3);
			setRanking(0);
		}
		
		
		public int getGrade() {
			return grade;
		}

		public void setGrade(int grade) {
			this.grade = grade;
		}

		public int getBan() {
			return ban;
		}

		public void setBan(int ban) {
			this.ban = ban;
		}

		public int getNum() {
			return num;
		}

		public void setNum(int num) {
			this.num = num;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getKorean() {
			return korean;
		}

		public void setKorean(int korean) {
			this.korean = korean;
		}

		public int getEnglish() {
			return english;
		}

		public void setEnglish(int english) {
			this.english = english;
		}

		public int getMath() {
			return math;
		}

		public void setMath(int math) {
			this.math = math;
		}

		public int getTotalScore() {
			return totalScore;
		}

		public void setTotalScore(int totalScore) {
			this.totalScore = totalScore;
		}

		public double getAvg() {
			return avg;
		}

		public void setAvg(double avg) {
			this.avg = avg;
		}

		public int getRanking() {
			return ranking;
		}

		public void setRanking(int ranking) {
			this.ranking = ranking;
		}
		
		public String toString() {
			String value = "등수 : " + getRanking() + "\n";
			value += getGrade( ) + "학년" + getBan() + "반 " + 
					getNum() + "번 " + getName() + "\n";
			value += "국어 : " + getKorean() + ", 영어 : " + getEnglish() + ", 수학 : " + getMath() + "\n";
			value += "총점 : " + getTotalScore() + "\n";
			value += "평균 : " + String.format("%.1f", getAvg()) + "\n";
			
			return value;
		}
}

package etc;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MySample1201_6 {
	
	public static int randomRange(int min, int max, Random random) {
		if(min > max) {
			return min;
		}
		
		//난수발생 - min부터 max값 사이 난수 발생
		return random.nextInt((max+1)-min)+min;
	}

	public static void main(String[] args) {
		Random random = new Random();
			
		//학생 리스트 작성
		List<Student> list = new ArrayList<Student>();
		
		//랜덤 점수 입력
		int i;
		
		for(i = 1 ; i <= 20 ; i++) {
			list.add(new Student(1,1,1, "홍길동"+i, 
								 randomRange(40, 100, random),
								 randomRange(40, 100, random),
								 randomRange(40, 100, random)));
		}
		
		//등수 산정 전 출력
		System.out.println("###########################");
		System.out.println("등수 산정 전 출력");
		System.out.println("###########################");
		for(i = 0 ; i < list.size() ; i++) {
			Student student = list.get(i);
			System.out.println(student);
		}
		
		//등수를 적용하기 위해 내림차순 정렬
		int j;
		Student tmp;
		
		for(i = 0 ; i < (list.size()-1) ; i++) {
			for(j = i+1 ; j < list.size() ; j++) {
				if(list.get(i).getTotalScore() < list.get(j).getTotalScore()) {
					tmp = list.get(i);
					list.set(i, list.get(j));
					list.set(j, tmp);
					
				}
			}
		}
		
		System.out.println();
		
		//등수 산정한 후 출력
		System.out.println("###########################");
		System.out.println("등수 산정 후 출력");
		System.out.println("###########################");
		
		int ranking = 0;		//등수
		int order = 0;			//동일 등수 증가 값
		
		Student student;
		
		//등수 산정 및 출력
		for( i = 0 ; i < list.size() ; i++) {
			student = list.get(i);
			
			if(i == 0) {
				//등수 포기 값으로 1로 설정
				ranking++;
				//동일 등수 증가 값도 1로 설정
				order++;
			}
			else {
				//총점이 같다면
				if(list.get(i-1).getTotalScore() == student.getTotalScore()) {
					//동일 등수시 증가값만 적용(등수 ranking 바로 앞과 동일)
					order++;
				}
				else {
					//총점이 틀리면(이전 등수에 동일 등수 증가 값을 더함)
					ranking += order;
					//동일 등수 증가 값 초기화
					order = 1;
				}
			}
			
			//등수 부여
			student.setRanking(ranking);
			
			//출력
			System.out.println(student);
		}		
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

** 예제 MySample1130 (예외처리 속 예외처리) **

package exec;

public class MySample1130 {

	public static void main(String[] args) {
		// 예외처리
		try {
				System.out.println("외부 try");
				
				try {
					System.out.println("내부 try");
					Exception e = new Exception();
					throw e;
				}
				catch(Exception e) {
					System.out.println("내부 try~catch exception : " + e);
					System.out.println("예외 던기지 한번 더");
					throw e;
				}
		}
		catch(Exception e) {
			System.out.println("외부 try~catch exception : " + e);
		}
		
		System.out.println("예외처리 끝");
	}
}

** 예제 MySample1130_2 (사용자 예외처리 = 클래스 예외처리) **

package exec;

import java.util.Scanner;

public class MySample1130_2 {
	static Scanner scn = new Scanner(System.in);
	
	static void ticketing(int age) throws AgeException{ //ticketing 호출하는 쪽에서 예외처리 해야한다.
		if(age < 20) {
			
			//AgeException e = new AgeException("나이 입력 오류");
			//throw e;
			//위 두줄을 한줄로
			throw new AgeException("나이 입력 오류");
		}
	}

	public static void main(String[] args) {
		// 예외처리 - 사용자 예외처리 (=클래스 예외처리)
		/*
		 * 문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료
		 */
		
		
		System.out.print("나이를 입력하세요.>");
		int age =scn.nextInt();
		
		try {
			ticketing(age);
		}
		catch(AgeException e) {
			e.printStackTrace();
		}
		
		System.out.println("main() 메소드 끝.");
		
	}
}


class AgeException extends Exception{	//Exception 상속 받아야함 (안받으면 Object상속받음)
	AgeException(){
		this("나이 입력 오류");
	}
	AgeException(String msg){
		super(msg);
	}
}

 

//문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료

//문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료

package exec;

import java.util.Scanner;

public class MySample1130_2 {
	static Scanner scn = new Scanner(System.in);
	
	static void ticketing(int age) throws AgeException{ //ticketing 호출하는 쪽에서 예외처리 해야한다.
		if(age < 20) {
			
			//AgeException e = new AgeException("나이 입력 오류");
			//throw e;
			//위 두줄을 한줄로
			throw new AgeException("나이 입력 오류");
		}
	}

	public static void main(String[] args) throws InterruptedException {		//Thread.sleep(1000); 사용하기위해 throws 해준다.
		// 예외처리 - 사용자 예외처리 (=클래스 예외처리)
		/*
		 * 문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료
		 */
		
		while(true) {
			
			System.out.print("나이를 입력하세요.>");
			int age = scn.nextInt();
			
			try {
				ticketing(age);
				System.out.println("티켓 발행 성공");
				break;
			}
			catch(AgeException e) {
				e.printStackTrace();
				//예쁘게 보이기위해 Thread.sleep(1000); 와 throws InterruptedException 사용해줌
				//위 e.printStackTrace(); 대신 아래문자열로 사용 가능
				System.out.println(e.getMessage());	
			}
			
			Thread.sleep(1000);			//1초 대기
			System.out.println();
			
		}
	}
}

class AgeException extends Exception{	//Exception 상속 받아야함 (안받으면 Object상속받음)
	AgeException(){
		this("나이 입력 오류");
	}
	AgeException(String msg){
		super(msg);
	}
}

** 예제 MySample1130_3 (예외처리)**

package exec;
//예외처리가 어디서 일어나는지 알아보기 위해 쓰인다.(흔하게 쓰이진 않음)
public class MySample1130_3 {

	public static void main(String[] args) {
		// 예외처리 (연결된 예외처리)
		
		try {
			install();
		}
		catch(InstallException e) {
			System.out.println("1111111111111111111111111");
			e.printStackTrace();
		}
		catch(Exception e) {
			System.out.println("2222222222222222222222222");
			e.printStackTrace();
		}
		finally {
			System.out.println("*************************");
		}
	}
	
	static void install() throws InstallException{
		try {
			startInstall();
			copyFiles();
		}
		catch(SpaceException e) {
			InstallException ie = new InstallException("설치중 예외발생11");
			//InstallException의 원인 예외를 SpaceException으로 지정
			ie.initCause(e);			//지정된 예외를 예외로 등록
			throw ie;
			
			//
		}
		catch(MemoryException e) {
			InstallException ie = new InstallException("설치중 예외발생22");
			ie.initCause(e);
			throw ie;
		}
		finally {
			deleteTempFiles();
		}
	}
	
	static void startInstall() throws SpaceException, MemoryException{
		
		if(!enoughSpace()) {
			throw new SpaceException("설치 공간이 부족함.");
		}
		
		if(!enoughMemory()) {
			throw new MemoryException("메모리가 부족함");
		}
	}
	
	
	static void copyFiles() {
		System.out.println("설치에 필요한 파일들을 복사.");
	}
	
	static boolean enoughSpace() {
		System.out.println("설치시 필요한 공간이 충분한지 확인.");
		return false;
	}
	
	static boolean enoughMemory() {
		System.out.println("설치시 필요한 메모리 확인");
		return true;
	}
	
	static void deleteTempFiles() {
		System.out.println("설치 후 설치시 사용한 임시파일 삭제.");
	}
	
}


class InstallException extends Exception{
	
	InstallException(String msg){
		super(msg);
	}

 




** Java.lang패키지 **

- 가장 기본이 되는 클래스들을 포함하고 있으며, import문 없이도 사용가능

 

Object클래스 : 모든 클래스의 최고 조상

Object 클래스의 메소드  설명
public Boolean equals(Object obj) 객체 자신과 객체 obj가 같은 객체인 기 (같으면 true)
public Class getClass() 객체 자신의 클래스 정보를 담고 있는 Class 인스턴스를 반환
public int hachCode() 객체 자신의 해시코드를 반화
public String toString() 객체 자신의 정보를 문자열로 반환

 

Object클래스에 equals메소드는 참조변수가 같은 객체를 참조하는 판다.

String 클래스의 epuals메소드는 주소값이 아닌 내용을 비교하도록 오버라이딩 되어있음.

public String toString{
                  reurn getCalss().getName() + "@" + integer.toHexString(hashCode());
                  //실행예) Card@19e0bfd
}

 

 


** 예제 MySample1130_4 **

package exec;

class  Value{
	
	int value;
	
	Value(int value){
		this.value = value;
	}
}

public class MySample1130_4 {

	public static void main(String[] args) {
		//java.lang 패키지
		Value v1 = new Value(20);
		Value v2 = new Value(20);
		
		if(v1.equals(v2)) {
			System.out.println("v1과 v2가 같습니다.");
		}
		else {
			System.out.println("v1과 v2가 다릅니다.");
		}
		
		v1 = v2;
		
		if(v1.equals(v2)) {
			System.out.println("v1과 v2가 같습니다.");
		}
		else {
			System.out.println("v1과 v2가 다릅니다.");
		}
	}
}

** 예제 MySample1130_5 **

package exec;

public class MySample1130_5 {

	public static void main(String[] args) {
		//equals 메소드 오버라이딩
		Person p1 = new Person(102345677722L);
		Person p2 = new Person(102345677722L);
		
		if(p1 == p2) {
			System.out.println("p1과 p2가 같습니다.");
		}
		else {
			System.out.println("p1과 p2가 다릅니다.");
		}
		
		if(p1.equals(p2)) {
			System.out.println("p1과 p2가 같다.*");
		}
		else {
			System.out.println("p1과 p2가 다르다.*");
		}
		
	}
}


class Person{
	
	long id;
	
	Person(long id){
		this.id = id;
	}
	
	@Override
	public boolean equals(Object obj) {	//Object 참조형을 받는다는 의미 - Object클래스 상속받는 모든 객체를 매개변수로 받을 수 있다.
		
		if(obj instanceof Person) {
			
			if(this.id == ((Person)obj).id) 
				return true;
			else
				return false;
			//if절 4줄을 아래 한 줄로 표현 가능
			//return this.id == ((Person)obj).id;
		}
		else
			return false;
	 }
}

** 예제 MySample1130_6 **

package exec;

public class MySample1130_6 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Card c1 = new Card();
		Card c2 = new Card("heart", 10);
		
		System.out.println("c1.toString : " + c1.toString());
		System.out.println("c2.toString : " + c2.toString());
		
		String str = new String("korea");
		String str1 = "korea";
		
		System.out.println("str : " + str);
		System.out.println("str.toString : " + str.toString());
		
		System.out.println("str1 : " + str1);
		System.out.println("str1.toString : " + str1.toString());
		
	}

}

class Card{
	String kind;
	int number;
	
	Card(){
		this("spade", 1);
	}
	
	Card(String kind, int number){
		this.kind = kind;
		this.number = number;
	}
	
	void test() {
		Card c = new Card();
		System.out.println(c.toString());
	}
	
	public String toString() {
		return "kind : " + this.kind + ", number : " + this.number;
	}
}



** String클래스 **

- 문자열을 위한 클래스로 문자열을 저장하고 이를 다루는데 필요한 메서드 제공

메서드 설명 예제 결과
int comareTo(String str) int l = "aaa".compareTo("aaa"); i = 0
String cocat(String str) String s1 = "Hello";
String s2 = s1.concat(" World");
s2 = "Hello World"
boolean equals(Object obj) String s = "Hello";
String s2 = s.equals( "Hello" );
s2 = ture;
int indexOf(int ch) String s = "Hello";
int idx1 = s.indexOf('o');
()에 숫자가 들어가면 문자열에서 숫자에 해당하는 문자반환
()에 문자가 들어가면 그 문자가 있는 위치 번호 반환
Index1 =4
int length() String s = "Hello";
int length = s.length();
lenght = 5
String[] split(String regex) String animals = "dog,cat,bear"
String[] arr = animals.split(",");
arr[0] = "dog"
arr[1] = "cat"
arr[2] = "bear"

 


 

** 예제 MySample1130_6 **

package exec;

import java.util.StringJoiner;

public class MySample1130_7 {

	public static void main(String[] args) {
		
		String str1 = "abc";	//문자열 리터럴 "abc"의 주소가 str1에 저장
		String str2 = "abc";	//문자열 리터럴 "abc"의 주소가 str2에 저장 
								//(결과는 str1과 str2는 문자열 "abc"를 같이 바라봄)
		
		System.out.println("String str1 = \"abc\";");
		System.out.println("String str2 = \"abc\";");
		
		System.out.println(str1);	//.toString()메소드 생략되어있음
		System.out.println(str2);
		System.out.println("str1 == str2 : " + (str1 == str2)); 		//String객체는 == 연산자 할 때 객체가 가지고 있는 값을 비교함.
		System.out.println("str1.equals(str2) : " + str1.equals(str2)); //String타입은 .equals로 비교하는 것이 좋음
		
		System.out.println();
		
		String str3 = new String("\"abc\"");		//새로운 String인스턴스 생성
		String str4 = new String("\"abc\"");		//새로운 String인스턴스 생성
		
		System.out.println(str3);
		System.out.println(str4);
		System.out.println("str3 == str4 : " + (str3 == str4));
		System.out.println("str3.equals(str4) : " + str3.equals(str4));
		
		System.out.println();
		/*
		 * 확장형 for문
		 * String[] arr = {"a", "b", "c"};
		 * for(String s : arr)
		 */
		
		String animals = "dog,cat,bear";
		String[] arr = animals.split(",");
		
		for(String s : arr) {
			System.out.print(s + " ");
		}
		
		System.out.println();
		
		System.out.println(String.join("-", arr));			//문자열과 문자열 사이에 "-"로 구분
		StringJoiner sj = new StringJoiner("/","[","]");	
		//문자열을 add할때 - 문자열과 문자열사이 들어갈것(-), 문자열 시작에 들어갈 것([), 문자열 끝에 들어갈 것(])
		
		for(String s : arr){
			sj.add(s);
		}
		
		System.out.println(sj.toString());
	}
}

 

* 결과

String str1 = "abc";
String str2 = "abc";
abc
abc
str1 == str2 : true
str1.equals(str2) : true

"abc"
"abc"
str3 == str4 : false


** 예제 MySample1130_7 **

package exec;

import java.util.StringJoiner;

public class MySample1130_7 {

	public static void main(String[] args) {
		
		String str1 = "abc";	//문자열 리터럴 "abc"의 주소가 str1에 저장
		String str2 = "abc";	//문자열 리터럴 "abc"의 주소가 str2에 저장 
								//(결과는 str1과 str2는 문자열 "abc"를 같이 바라봄)
		
		System.out.println("String str1 = \"abc\";");
		System.out.println("String str2 = \"abc\";");
		
		System.out.println(str1);	//.toString()메소드 생략되어있음
		System.out.println(str2);
		System.out.println("str1 == str2 : " + (str1 == str2)); 		//String객체는 == 연산자 할 때 객체가 가지고 있는 값을 비교함.
		System.out.println("str1.equals(str2) : " + str1.equals(str2)); //String타입은 .equals로 비교하는 것이 좋음
		
		System.out.println();
		
		String str3 = new String("\"abc\"");		//새로운 String인스턴스 생성
		String str4 = new String("\"abc\"");		//새로운 String인스턴스 생성
		
		System.out.println(str3);
		System.out.println(str4);
		System.out.println("str3 == str4 : " + (str3 == str4));
		System.out.println("str3.equals(str4) : " + str3.equals(str4));
		
		System.out.println();
		/*
		 * 확장형 for문
		 * String[] arr = {"a", "b", "c"};
		 * for(String s : arr)
		 */
		
		String animals = "dog,cat,bear";
		String[] arr = animals.split(",");
		
		for(String s : arr) {
			System.out.print(s + " ");
		}
		
		System.out.println();
		
		System.out.println(String.join("-", arr));			//문자열과 문자열 사이에 "-"로 구분
		StringJoiner sj = new StringJoiner("/","[","]");	
		//문자열을 add할때 - 문자열과 문자열사이 들어갈것(-), 문자열 시작에 들어갈 것([), 문자열 끝에 들어갈 것(])
		
		for(String s : arr){
			sj.add(s);
		}
		
		System.out.println(sj.toString());

	}
}



** 날짜와 시간 **

Calendar 클래스 : 추상 클래스이므로 객체를 직접생성할 수 없고, 메서드를 통해서 완전히 구현된 인스턴스를 얻어야 한다.

 

* Calendar클래스의 주요 상수(static final int) - 아래 표에는 final이 생략되어 있다.

cf) 상수 변수는 모두 대문자를 사용하고, 단어와 단어 사이에는 _(언더바)를 넣어준다.

상수 사용방법 설명
static int YEAR Calendar.YEAR 현재 년도를 가져온다
static intMONTH Calendar.MONTH 현재 월을 가져온다.(1월은 0)
static intDATE Calendar.DATE 현재 월의 날짜를 가져온다.
static intWEEK_OF_YEAR Calendar.WEEK_OF_YEAR 현재 년도의 몇째 주
static intWEEK_OF_MONTH Calendar.WEEK_OF_MONTH 현재 월의 몇째 주
static intDAY_OF_YEAR Calendar.DAY_OF_ YEAR 현재 년도의 날짜
static intDAY_OF_MONTH Calendar.DAY_OF_ MONTH 현재 월의 날짜(DATE와 동일)
static intDAY_OF_WEEK Calendar.DAY_OF_ WEEK 현재 요일(일요일1, 토요일7)
static intHOUR Calendar.HOUR 현재시간 (12시간제)
static intHOUR_OF_DAY Calendar.HOUR_OF_DAY 현재시간 (24시간제)
static intMINUTE Calendar. MINUTE 현재 분
static intSECOND Calendar. SECOND 현재 초

 

cf) 추상클래스의 추상메소드를 쓰는 이유 -> 자식클래스가 반드시 그 메소드를 정의해야함을 부여

     인터페이스 

 

* Calendar클래스 메소드

   
   
   
   
   
   
   
   
   
   
   
   

 

Calendar cal = new Calendar();          //에러. 추장클래스는 인스턴스 생성불가

Calendar cal = Calendar.getInstance();   //이렇게 객체생성 해야함

 


** 예제 MySample1130_8 (캘린더) **

package exec;

import java.util.Calendar;

public class MySample1130_8 {

	public static void main(String[] args) {
		// 캘린더 클래스
		
		Calendar today = Calendar.getInstance();
		
		System.out.println("년도 : " + today.get(Calendar.YEAR));
		System.out.println("월, 1월(0) : " + today.get(Calendar.MONTH));
		System.out.println("올해의 몇째 주 : " + today.get(Calendar.WEEK_OF_YEAR));
		System.out.println("이번달의 몇째 주 : " + today.get(Calendar.WEEK_OF_MONTH));
		System.out.println("이달의 며칠 : " + today.get(Calendar.DATE));
		System.out.println("올해의 며칠 : " + today.get(Calendar.DAY_OF_YEAR));
		System.out.println("요일1(일요일) : " + today.get(Calendar.DAY_OF_WEEK));
		System.out.println("이달의 몇째 요일 : " + today.get(Calendar.DAY_OF_WEEK_IN_MONTH));
		System.out.println("오전/오후(0:오전, 1:오후) : " + today.get(Calendar.AM_PM));
		System.out.println("시간(0~11) : " + today.get(Calendar.HOUR));			//12시기준
		System.out.println("시간(0~23) : " + today.get(Calendar.HOUR_OF_DAY));	//24시기준
		System.out.println("분(0~59) : " + today.get(Calendar.MINUTE));
		System.out.println("초(0~59) : " + today.get(Calendar.SECOND));
		System.out.println("이달의 마지막날 : " + today.getActualMaximum(Calendar.DATE));
		
		final String[] DAY_OF_WEEK = {"","일", "월", "화", "수", "목", "금", "토"};
		
		Calendar date1 = Calendar.getInstance();
		Calendar date2 = Calendar.getInstance();
		
		date1.set(2001, 3, 8);
		
		System.out.println("date2 : " + toString2(date2) + DAY_OF_WEEK[date2.get(Calendar.DAY_OF_WEEK)] + "요일입니다.");
		System.out.println("date1 : " + toString2(date1) + DAY_OF_WEEK[date1.get(Calendar.DAY_OF_WEEK)] + "요일입니다.");
		
		
		
		System.out.println();
		
		
		
		System.out.println("=== 1일 후 ===");
		date2.add(Calendar.DATE, 1);
		System.out.println(toString2(date2));
		
		System.out.println("=== 5달 전 ===");
		date2.add(Calendar.MONTH, -5);
		System.out.println(toString2(date2));
		
		System.out.println("=== 31일 후 ===(roll)");
		date2.roll(Calendar.DATE, 20);				//roll -> 일만 바꿔준다.(월은 변경되지 않음)
		System.out.println(toString2(date2));
		
		System.out.println("=== 31일 후 ===(add)");
		date2.add(Calendar.DATE, 20);				//add -> 월과 일을 같이 바꿔준다.
		System.out.println(toString2(date2));
		
	}
	
	public static String toString2(Calendar date) {
		return date.get(Calendar.YEAR) + "년 " + (date.get(Calendar.MONTH)+1) + "월 " + date.get(Calendar.DATE)+ "일 ";
	}
	
}

** 예제 MySample1130_9 (캘린더) **

// 월과 년을 입력받았을 때 날짜를 알려주는 프로그램

package exec;

import java.util.Calendar;

public class MySample1130_9 {

	public static void main(String[] args) {
		// 월과 년을 입력받았을 때 날짜를 알려주는 프로그램
		
		System.out.println("args.length : " + args.length);
		
		if(args.length != 2) {
			System.out.println("args 오류 ... 년과 월을 입력하세요.>");
			return;		//밑에 있는거 실행하지 않고 나를 호출한 곳으로 돌아감 (여기서는 JVM이라서 프로그램종료)
		}
		
		System.out.println("성공 ...");
		
		
		//* args배열에 값입 력하는 법 
		//Project Explorer의 현재 클래스 우클릭 -> run as -> run configurations... -> arguments -> program arguments에 스페이스 기준으로 입력
		
		int year = Integer.parseInt(args[0]);
		int month = Integer.parseInt(args[1]);
		
		Calendar sDay = Calendar.getInstance();		//시작일
		Calendar eDay = Calendar.getInstance();		//끝일
		
		sDay.set(year, month-1, 1);
		//해당월의 마지막날 - 입력월의 마지막날 getActualMaximun 이용
		eDay.set(year, month-1, sDay.getActualMaximum(Calendar.DATE));
		//1일이 속한 주의 일요일로 날짜 선정
		sDay.add(Calendar.DATE, -sDay.get(Calendar.DAY_OF_WEEK) + 1);
		//말일이 속한 주의 토요일 날짜 선정
		eDay.add(Calendar.DATE, 7 - eDay.get(Calendar.DAY_OF_WEEK));
		
		System.out.println(" " + year + "년 " + month + "월");
		System.out.println(" 일  월  화  수  목  금  토");
		
		//시작일부터 마지막일까지 (sDay <= eDay) 1일씩 증가 시키면서
		//일(Calendar.DATE)출력
		int day;
		for(int n = 1 ; sDay.before(eDay)||sDay.equals(eDay) ; sDay.add(Calendar.DATE, 1)) {
			day = sDay.get(Calendar.DATE);
			System.out.print((day < 10) ? ("  " + day) : (" " + day));
			
			if(n++ % 7 == 0) System.out.println();
		}
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

** 예외처리 ( exception handling) **

* 예외처리란?

- 프로그램 실행시 발생할 수 있는 예기치 못한 예외의 발생에 대비한 코드를 작성하는 것

- 목적 : 예외 발생시 실행중인 프로그램의 갑작스런 비정상 종료를 막고, 비정상 종료를 막아 정상적인 실행 상태를 유지할 수 있도록 하는 것

- 구조 

try{
		예외처리하길 원하는 실행코드;
}

// catch는 여러개 사용가능함
catch(Exception1 e1){
		Exception1이 발생했을 경우, 처리하기위한 문장
}

catch(Exception2 e2){
		Exception2이 발생했을 경우, 처리하기위한 문장
}

....

finally{
		예외발생 여부와 상관없이 무조건 실행될 코드
}

 

 

프로그램이 실행 중 어떤 원인의 의해서 오작동을 하거나 비정상적으로 종료되는 경우를 프로그램 에러 또는 오류하고 함.

프로그램이 실행되는 도중 발생하는 예외를 처리하기 위해

try / catch / finally 문을 사용

컴파일 에러 - 컴파일 시에 발생하는 에러
런타임 에러 - 실행 시에 발생하는 에러
논리적 에러 - 실행은 되지만, 의도와 다르게 동작하는 것

 

* 자바에서 실행 시 발생할 수 있는 프로그램 오류

- 에러(error) : 프로그램 코드에 의한 수습될 수 없는 심각한 오류

- 예외(exception) : 프로그램 코드에 의해서 수습될 수 있는 오류

 

예외가 발생하더라도 프로그래머가 이에대한 적절한 코드를 미리 작성해 놓아 프로그램이 비정상적으로 종료되는 것을 막는 것을 의미함.

 

- 예외 클래스 계층구조 : 모든 예외의 최고 조상은  Exception클래스

 

FileNotFoundException

ClassNotFoundException

DataFormatException

 

ArrayIndexOutOfBoundsException




** 예제 exec Pakage _ MySample1129 (예외처리) **

package exec;

public class MySample1129 {

	public static void main(String[] args) {
		// 예외처리
		
		int[] a = {2, 0};
		int b = 4;
		
		//int c =a[2];		//먼저 실행 후 오류 확인
		
		try {
			int c = b / a[2];				//int c = a[2];
			System.out.println("c " + c);
		}
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println("배열 인덱스 오류 발생");
		}
//		catch(ArithmeticException e) {
//			System.out.println("0으로 나눌수 없습니다. : " + e);
//		}
		
		//프로그램은 위에서 아래로 흐르기에 가장 최고조상인 Exception 은 가장 아래에 있어야 오류 안난다.
		catch(Exception e) {
			System.out.println("뭔지몰라 오류 발생 : " + e);
		}
		finally {	
			System.out.println("무조건 실행됨");
		}
		
		System.out.println("try~catch 끝.");
	}

}

** 예제 MySample1129 _ 2 (예외처리) **

package exec;

public class MySample1129_2 {

	public static void main(String[] args) {
		// 예외처리
		//0으로 나누었을 떄 "0으로 나눌 수 없습니다." 메세지 출력 후 계속 진행
		int number = 10;
		int result = 0;
		int i;
		
//		try {
//			for(i = 0 ; i < 10 ; i++) {
//				result = number/(int)(Math.random( )* 10);
//				System.out.println("result " + result); 
//			} 
//		}
//		catch(ArithmeticException e) {
//			System.out.println("0으로 나눌 수 없습니다.: " + e);
//		}
//		
//		
//			for(i = 0 ; i < 10 ; i++) {
//				try {
//					result = number/(int)(Math.random( )* 10);	//0~9
//					System.out.println("result " + result);
//				}
//				catch(ArithmeticException e) {
//					System.out.println("0으로 나눌 수 없습니다.: " + e);
//				}
//				 
//			} 
		
		//실행순서
		System.out.println("1");
		
		try {
			System.out.println("2");
			
			int a = 5 / 0;
			
			System.out.println("3");
		}
		catch(Exception e){
			System.out.println("4");
		}
		finally {
			System.out.println("4-2");
		}
		
		System.out.println("5");
		
	}
}

** 예제 MySample1129_3 (예외처리) **

package exec;

public class MySample1129_3 {

	public static void main(String[] args) {
		// 예외처리
		System.out.println("1");
		
		try {
			System.out.println("2");
			System.out.println(2 / 0);
			System.out.println("3");
		}
		catch(ArithmeticException e) {
			System.out.println("4");
			
			if(e instanceof ArithmeticException)
				System.out.println("true");
			
			System.out.println("ArithmeticException");
			e.printStackTrace();		//디버깅용
			
			
			System.out.println("예외 메세지 : " + e.getMessage());
		}
		catch(Exception e) {
			System.out.println("5");
			System.out.println("예외 메세지 : " + e.getMessage());
		}
		
		System.out.println("6");
	}
}

** 예제 MySample  1129_4 (예외발생시켜보기)**

package exec;

public class MySample1129_4 extends Exception{

	MySample1129_4(String a){
		super(a);
	}
	
	public static void main(String[] args) {
		//예외발생
		
		try {
			MySample1129_4 e = new MySample1129_4("일부러 오류 발생 시켰음.");
			//Exception e = new Exception("일부러 오류 발생 시켰음.");
			throw e;		//예외를 발생시키는 throw
		}
		catch(Exception e) {
			System.out.println("에러메세지 : " + e.getMessage());
		}
		
		System.out.println("프로그램 정상 종료 되었음.");
	}
}

** 예제 MySample 1129_5 (메서드예외) **

package exec;

public class MyClass1129_5 {

	public static void main(String[] args) {
		
		// 예외처리 - 메서드 예외
		// 예)void method() throws Exception1,Exception2,.....{		}
		
		try {
			method1();
			System.out.println("555555555555555");
		}
		catch(Exception e) {
			System.out.println("e.message : " + e.getMessage());
		}
		
		System.out.println("main 끝.");
	}
	
	//메소드 예외처리 : throws Exception 있으면 모든 예외를 나를 호출한 곳에서 try/catch.
	//throws Exception 메서드에 예외가 발생하면 더이상 실행하지 않고 나를 호출한 곳으로 돌아간다.
	static void method1() throws Exception{		
		System.out.println("111111111111111");
		method2();
		System.out.println("222222222222222");
	}
	
	static void method2() throws Exception{
		System.out.println("333333333333333");
		int c = 5 / 0;
		System.out.println("444444444444444");
	}
}

** 예제 MySample 1129_6 ( 예외처리 - finally블럭 ) **

package exec;

public class MySample1129_6 {

	public static void main(String[] args) {
		// 예외처리 - finally블럭
		
		try {
			startInstall();
			copyFiles();
			//deleteTempFiles();
		}
		catch(Exception e) {
			e.printStackTrace();
			//deleteTempFiles();
		}
		finally {
			deleteTempFiles();		//try/catch 둘다사용해야하는 경우는 보통 finally로 빼준다.
		}
		
		method1();
		System.out.println("method1() 실행 끝나고 main으로 돌아옴.");
	}
	
	static void startInstall() {
		System.out.println("프로그램 설치에 필요한 준비작업하는 영역..");
	}
	
	static void copyFiles() {
		System.out.println("파일들을 복사하는 영역..");
	}
	
	static void deleteTempFiles() {
		System.out.println("임시파일들 삭제하는 영역..");
	}
	
	static void method1() {
		try {
			System.out.println("method1() 실행시작");
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			System.out.println("method1() finally블럭실행");
		}
	}
}

** 예제 MySample 1129_7 (클래스 예외처리 - 예외클래스 생성 후 다른클래스 메소드에서 예외처리) **

package exec;

import java.util.Scanner;

public class MySample1129_7 {

	static Scanner scn = new Scanner(System.in);	//main메소드가 static이라서
	
	public static int inputScore() throws ScoreException{	//예외 클래스 만든것을 메소드에서 예외처리함
		int score = scn.nextInt();
		
		if(score < 0 || score > 100){
			ScoreException ex = new ScoreException("점수는 0~100점 사이 입력하세요.");
			throw ex;
		}
		
		return score;
	}
	
	public static void main(String[] args) {
		// 예외처리(클래스)
		
		try {
			System.out.print("국어 점수 입력>");
			int kor = inputScore();
			System.out.println("국어 점수는 " + kor + "점 입니다.");
			
			System.out.print("영어 점수 입력>");
			int eng = inputScore();
			System.out.println("영어 점수는 " + eng + "점 입니다.");
		}
		catch(ScoreException ex) {
			System.out.println("오류메세지 : " + ex.getMessage());
		}
		finally {
			System.out.println("프로그램 종료합니다.");
		}
	}
}

class ScoreException extends Exception{			//예외처리클래스
	ScoreException(){
		super("점수 입력 오류");
	}
	
	ScoreException(String nsg){
		super(nsg);
	}
}

** 문제 MySample1129_8 (예외처리) **

// 예외처리 - 문제
/*
 * 20번 반복해서 랜덤발생을 0~9까지 발생시킨후 랜덤값으로 나눈 결과를 화면에 출력하되 0으로 나누면 오류 발생함.
 * ArithmeticException 에 대한 예외처리를 적용하고 예외에 대한 출력은 0으로 처리하고, 0으로 나눈 횟수 발생한
 * 건수를 최종 출력하는 프로그램
 * 출력예)
 * 16
 * 20
 * 11
 * 0 -> 랜덤발생이 0으로 되어 예외처리부분.
 * 33
 * 100
 * ...
 * 0 발생 건수 : 1건
 * 단, number = 100; 으로 초기 설정 후 (int)(Math.random() * 10); 처리함
 */

package exec;

public class MySample1129_8 {

	public static void main(String[] args) {
		// 예외처리 - 문제
		/*
		 * 20번 반복해서 랜덤발생을 0~9까지 발생시킨후 랜덤값으로 나눈 결과를 화면에 출력하되 0으로 나누면 오류 발생함.
		 * ArithmeticException 에 대한 예외처리를 적용하고 예외에 대한 출력은 0으로 처리하고, 0으로 나눈 횟수 발생한
		 * 건수를 최종 출력하는 프로그램
		 * 출력예)
		 * 16
		 * 20
		 * 11
		 * 0		-> 랜덤발생이 0으로 되어 예외처리부분.
		 * 33
		 * 100
		 * ...
		 * 0 발생 건수 : 1건
		 * 단, number = 100; 으로 초기 설정 후 (int)(Math.random() * 10); 처리함
		 */
		
		int number = 100;
		int result, cnt = 0;
		int i;
		
//		for (i = 0 ; i < 20 ; i++) {
//			try {
//				result = number / (int)(Math.random() * 10);
//				System.out.println(result);
//			}
//			catch(ArithmeticException a) {
//				result = 0;
//				cnt++;
//				System.out.println(result);
//			}
//		}	
//		System.out.println("0 발생 건수 : " + cnt);
		
//		//다른방법 (깔끔함)
//		for (i = 0 ; i < 20 ; i++) {
//			try {
//				result = number / (int)(Math.random() * 10);
//			}
//			catch(ArithmeticException a) {
//				result = 0;
//				cnt++;
//			}
//			finally {
//				System.out.println(result);
//			}
//		}	
//		System.out.println("0 발생 건수 : " + cnt);	
		
		
		//결과는 위화 동일하며 try~catch문을 사용하지 않고 프로그램 구현.
		

		for (i = 0 ; i < 20 ; i++) {
			
			int tmp = (int)(Math.random() * 10);
			
			if(tmp != 0) {
				result = number / tmp;
			}
			
			else {
				result = 0;
				cnt++;
			}
			System.out.println(result);
		}	
		System.out.println("0 발생 건수 : " + cnt);
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 ** 인터페이스 (interface) **

자바에서 다중상속은 지원하지 않으므로, 인터페이스를 통해 다중상속 지원

다른 클래스를 작성할 때 기본이 되는 틀을 제공하면서, 다른 클래스 사이의 중간 매개 역할 까지 담당하는 추상 클래스를 의미함

 

추상 클래스 - 추상메소드, 생성자, 필드, 일반 메소드로 포함

인터페이스 - 오로지 추상 메소드( public abstract )와 상수( public static final )만을 포함

 

인터페이스클래스에 있는 메소드는 모두 추상메소드 → abstract 를 쓰지않아도 컴파일러자 자동으로 추상메소드로 읽어준다.

 

문법) 인터페이스이름 = 클래스이름

문법)

접근제어자 interface 인터페이스이름{

       public static final 타입 상수이름 = 값;
       ...
       public abstract 리턴타입
                     메소드이름(매개변수목록);
       ...
}

//인터페이스를 상속 받을 때 문법
class 클래스이름 implements 인터페이스이름 {...}

//인터페이스이름자리에 , 로 여러개의 인터페이스클래스 명 올 수 있다.

 

모든 필드는 public static final
모든 메소드는 public abstract
제어자( public static final , public abstract )는 생략 가능하며 생략된 제어자는 컴파일시 자동 추가



** 예제 1128 **

package inter;

interface Animal{
	public static final int A = 10;		//public static final 생략 가능
	public abstract void cry();			//public abstract 생략 가능
}

class Cat implements Animal{
	public void cry() {
		System.out.println("야옹야옹..");
	}
}

class Dog implements Animal{
	public void cry() {
		System.out.println("멍멍..");
	}
}

public class MySample1128 {

	public static void main(String[] args) {
		// 인터페이스
		
		Cat c = new Cat();
		Dog d = new Dog();
		
		c.cry();
		d.cry();
	}
}

** 예제 1128_2 **

package inter;

interface Providable{
	public abstract void leisureSports();	//레저스포즈
	public abstract void sightSeeling();	//관광
	public abstract void food();			//음식
}

class KoreaTour implements Providable{
	public void leisureSports() {
		System.out.println("한강에서 수상스키 투어");
	}
	public void sightSeeling() {
		System.out.println("경복궁 관광 투어");
	}
	public void food() {
		System.out.println("불고기");
	}
}

class TourGuide{
	private Providable tour = new KoreaTour();
	
	public void leisureSports() {
		tour.leisureSports();
	}
	
	public void sightSeeling() {
		tour.sightSeeling();
	}
	
	public void food() {
		tour.food();
	}
}

public class MySample1128_2 {

	public static void main(String[] args) {
		// 인터페이스 (캡슐, 상속, 다형성)
		TourGuide guide = new TourGuide();
		guide.leisureSports();
		guide.sightSeeling();
		guide.food();
	}
}

** 문제 1125_3 **

package inter;

/*
 문제) 인터페이스 Animal2 와 Pet을 정의하며, Animal2 클래스는 울음소리(cry)를 Pet클래스는 움직임(play)를 정의함.
 	  고양이2 클래스와 강아지2 클래스에서 울음소리와 움직임에 대한 재정의를 구현함.
 	  단, 고양이는 울음소리는 "야오야용" 움직임은 "폴짝폴짝 뛰어다니기"로 출력하고
 	  	 강아지는 울음소리는 "멍멍" 움식임은 "산책하기"로 출력함.
 */

interface Animal2{
	public abstract String cry();
}

interface Pet{
	public abstract void play();
}

class Cat2 implements Animal2, Pet{
	public String cry() {
		return "야옹야옹";
	}
	public void play() {
		System.out.println("폴짝폴짝");
	}
}

class Dog2 implements Animal2{
	public String cry() {
		return "몽몽";
	}
	public void play() {
		System.out.println("산책하기");
	}
}

public class MySample1128_3 {

	public static void main(String[] args) {
		// 인터페이스를 통한 다중상속 (implements A, B)
		
		Dog2 d = new Dog2();
		Cat2 c = new Cat2();
		
		System.out.println(c.cry());
		c.play();
		System.out.println();
		System.out.println(d.cry());
		d.play();
	}
}

** 예제 1128_4 **

package inter;

interface Gamer{
	public static final int GAME_MAX_LEVEL = 100;
	
	public abstract void doGame();
}

interface Singer{
	int AUDITION_MAX_CHANCE = 10;	//public static final 이 생략됨
	int GAME_MAX_LEVEL = 99;		//public static final 이 생략됨
	
	void singSong();				//public abstract 생략됨
}

class Student implements Gamer, Singer{
	String name;
	int score;
	
	Student(String name, int score){
		this.name = name;
		this.score = score;
	}
	
	public void doGame() {
		System.out.println(name + "은 게임을 합니다.");
	}
	
	public void singSong() {		//메소드 오버라이딩하려면 접근지정자까지 일치해야해서 생략된 public써줘야한다.
		System.out.println(name + "은 노래를 부릅니다.");
	}
	
}

public class MySample1128_4 {

	public static void main(String[] args) {
		// 인터페이스 다중상속
		
		Student s = new Student("김둘리", 83);
		System.out.println("게임의 최고 레벨(Gamer) : " + Gamer.GAME_MAX_LEVEL);
		System.out.println("가수의 최고 레벨(Singer) : " + Singer.GAME_MAX_LEVEL);
		
		s.doGame();
		System.out.println(s.name + "의 점수 : " + s.score);
		System.out.println("오디션 최대 기회 : " + Singer.AUDITION_MAX_CHANCE);
		
	}
}

** 문제 inter2 pakage (RemoteControl) **

package inter2;

public interface RemoteControl {
	public static final int MAX_VOLUME = 10;
	public static final int MIN_VOLUME = 0;
	
	void turnOn();
	public abstract void turnOff();
	public abstract void setVolume(int volume);
}

/*
 turnOn 은 "TV를 켭니다." 또는 "오디오를 켭니다." / turnOff는 "TV를 끕니다." 또는 "오디오를 끕니다."
 setVolume은 max값과 min값에 대한 체크 후 tv는 "현재 TV볼륨은 : 5", 오디오는 "현재 오디오볼륨은 : 7"
 출력예)1111111111
 	  TV를 켭니다.
 	  현재 TV볼륨 : 5
 	  2222222222
 	  오디오를 켭니다.
 	  현재 오디오볼륨 : 5
      오디오를 켭니다.
	  현재 오디오볼륨 : 5
 	  3333333333
 	  오디오를 겹니다.
 	  현재 오디오 볼륨 : 5
 	  4444444444
 	  TV를 켭니다.
 	  현재 TV볼륨은 : 5
 */

package inter2;

public class Tv implements RemoteControl{	
	private int volume;
	
	public void turnOn() {
		System.out.println("TV를 켭니다.");
	}
	public void turnOff() {
		System.out.println("TV를 끕니다.");
	}
	
	public void setVolume(int volume) {
		if (volume > MAX_VOLUME) {
			this.volume = MAX_VOLUME;
		}
		else if(volume < MIN_VOLUME) {
			this.volume = MIN_VOLUME;
		}
		else {
			this.volume = volume;
		}
		System.out.println("현재 TV볼륨은 : " + getVolume());
	}
	public int getVolume() {
		return this.volume;
	}
}

package inter2;

public class Audio implements RemoteControl{
	private int volume;		//인스터스변수의 접근자가 private이면 보통 set/get메소드 사용한다.
	
	public void turnOn() {
		System.out.println("오디오를 켭니다.");
	}
	public void turnOff() {
		System.out.println("오디오를 끕니다.");
	}
	
	public void setVolume(int volume) {
		if (volume > MAX_VOLUME) {
			this.volume = MAX_VOLUME;
		}
		else if (volume < MIN_VOLUME) {
			this.volume = MIN_VOLUME;
		}
		else {
			this.volume = volume;
		}
		System.out.println("현재 TV볼륨은 : " + getVolume());
	}
	public int getVolume() {
		return this.volume;
	}
}

package inter2;

public class MyClass {
	
	RemoteControl rc = new Tv();
	
	MyClass(){
		
	}
	
	MyClass(RemoteControl rc){
		this.rc = rc;
		rc.turnOn();	//this.rc.turnOn(); -> 둘다 같은의미 (this.rc 에 매개변수 rc를 대입했기때문)
		rc.setVolume(5);
		this.rc.turnOn();
		this.rc.setVolume(5);
	}
	
	void methodA() {
		RemoteControl rc = new Audio();
		rc.turnOn();
		rc.setVolume(5);
	}
	
	void methodA(RemoteControl rc) {		//메소드 오버로딩
		rc.turnOn();
		rc.setVolume(5);
	}
}

package inter2;

public class MyClassMain {

	public static void main(String[] args) {
		// 인터페이스
		
		/*출력예)1111111111
	  	TV를 켭니다.
	  	현재 TV볼륨 : 5
	  	2222222222
	  	오디오를 켭니다.
	  	현재 오디오볼륨 : 5
	  	오디오를 켭니다.
	  	현재 오디오볼륨 : 5
	  	3333333333
	  	오디오를 겹니다.
	  	현재 오디오 볼륨 : 5
	  	4444444444
	  	TV를 켭니다.
	  	현재 TV볼륨은 : 5
		*/
		
		System.out.println("1111111111");
		MyClass myClass1 = new MyClass();
		myClass1.rc.turnOn();
		myClass1.rc.setVolume(5);
		
		System.out.println("2222222222");	//MyClass에서 생성자를 통해
		Audio a = new Audio();
		MyClass myClass2 = new MyClass(a);	//new MyClass(new Audio()); 사용해도된다 (후에 a 사용없을시)
		
		System.out.println("3333333333");	//MyClass의 매개변수 없는 메소드를 통해
		MyClass myClass3 = new MyClass();
		myClass3.methodA();
		
		System.out.println("4444444444");	//MyClass의 매개변수 있는 메소드를 통해
		MyClass myClass4 = new MyClass();
		myClass4.methodA(new Tv());
	}
}

** 예제 inter3 pakage (그래픽카드) **

package inter3;

public interface GraphicsCard {
	
	//제조사
	public abstract String company();
	//모델
	public String model();
	//메모리
	public int memory();
	//출력
	public void write(PointColor pointcolor);
}

package inter3;

public class Rgb {
	private int red;
	private int green;
	private int blue;
	
	public Rgb() {
		this(0,0,0);
	}
	
	public Rgb(int red, int green, int blue) {
		this.red = red;
		this.green = green;
		this.blue = blue;
	}
	
	public int getRed() { 
		return this.red;
	}
	public void setRed(int red) {
		this.red = red;
	}
	
	public int getGreen() {
		return this.green;
	}
	public void setGreen(int green) {
		this.green = green;
	}
	
	public int getBlue() {
		return this.blue;
	}
	public void setBlue(int blue) {
		this.blue = blue;
	}
}

package inter3;

public class PointColor {
	//x좌표값
	private int x;
	//y좌표값
	private int y;
	//RGB색상표
	private Rgb rgb;
	
	public PointColor() {
		this(0,0,new Rgb());
	}
	public PointColor(int x, int y, Rgb rgb) {
		this.x = x;
		this.y = y;
		this.rgb = rgb;
	}
	
	public Rgb getRgb() {
		return this.rgb;
	}
	public void setRgb(Rgb rgb) {
		this.rgb = rgb;
	}
	
	public int getX() {
		return this.x;
	}
	public void setX(int x) {
		this.x = x;
	}
	
	public int getY() {
		return this.y;
	}
	public void setY(int y) {
		this.y = y;
	}
}

package inter3;

public class NvidiaGeForce implements GraphicsCard{
	
	private String company;
	private String model;
	private int memory;
	
	NvidiaGeForce(String model, int memory){
		company = "NVIDIA";
		this.model = model;
		this.memory = memory;
	}
	
	//제조사
	public String company() {
		return this.company;
	}
	//모델
	public String model() {
		return this.model;
	}
	//메모리
	public int memory() {
		return this.memory;
	}
	//출력
	public void write(PointColor pointColor) {
		if(pointColor != null) {
			Rgb rgb = pointColor.getRgb();
			System.out.println("---" + company + "GraphicsCard 출력");
			System.out.println("1.좌표를 구한다.");
			System.out.println("x : " + pointColor.getX());
			System.out.println("y : " + pointColor.getY());
			System.out.println("2.color 구성.");
			
//			if(rgb != null) {
//				System.out.println("Rgb : " + rgb.getRed());
//				System.out.println("Green : " + rgb.getGreen());
//				System.out.println("Blue : " + rgb.getBlue());
//			}
			
			//바로 위 주석을 아래와 같이 변경 가능.
			if(pointColor.getRgb() != null) {
				System.out.println("Rgb : " + pointColor.getRgb().getRed());
				System.out.println("Green : " + pointColor.getRgb().getGreen());
				System.out.println("Blue : " + pointColor.getRgb().getBlue());
			}

			System.out.println("3.모니터 좌표에 색상출력.");
			
		}
	}
}

package inter3;

public class AmdRadeon implements GraphicsCard{
	
	private String company;
	private String model;
	private int memory;
	
	public AmdRadeon(String model, int memory) {
		this.company = "AMD";
		this.model = model;
		this.memory = memory;
	}
	
	//제조사
	public String company() {
		return this.company;
	}
	//모델
	public String model() {
		return this.model;
	}
	//메모리
	public int memory() {
		return this.memory;
	}
	//출력
	public void write(PointColor pointColor) {
		if(pointColor != null) {
			Rgb rgb = pointColor.getRgb();
			
			System.out.println("---" + company + "GraphicsCard 출력");
			System.out.println("1.color를 구성한다.");
			
			if(rgb != null) {
				System.out.println("Blue : " + rgb.getBlue());		//pointColor.getRgb().getBlue()
				System.out.println("Red : " + rgb.getRed());		//pointColor.getRgb().getBlue()
				System.out.println("Green : " + rgb.getBlue());		//pointColor.getRgb().getBlue()
			}
			
			System.out.println("2.좌표를 구한다.");
			System.out.println("x : " + pointColor.getX());
			System.out.println("y : " + pointColor.getY());
			System.out.println("3.여기서 모니터 좌표에 색상 출력");
			
		}
	}
	//제너레이트 사용법 : Source -> Generate Getters and Setters -> selectAll
	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public int getMemory() {
		return memory;
	}

	public void setMemory(int memory) {
		this.memory = memory;
	}
}

package inter3;

public class GraphicsCardMain {
	//.java 에있는 인스턴스변수(private)는 set/get메서드로 접근한다.
	
	//운영체제에서 그래픽 출력
	public void operatingSystemWrite(GraphicsCard graphicsCard, PointColor pointColor) {
		if (graphicsCard != null) {
			System.out.println("그래픽 카드 출력");
			System.out.println("회사명 : " + graphicsCard.company());
			System.out.println("모델명 : " + graphicsCard.model());
			System.out.println("메모리 : " + graphicsCard.memory());
			graphicsCard.write(pointColor);
		}
	}

	public static void main(String[] args) {
		//인터페이스 예제 
		
		//라데온 그래픽 카드 생성
		GraphicsCard amdRadeon = new AmdRadeon("Rx 5000", 4096);
		
		//엔비디아 그래픽 카드 생성
		NvidiaGeForce nvidiaGeForce = new NvidiaGeForce("Gefpre GT 710", 2048);
		
		//포인트 컬러 생성
		PointColor pointColor = new PointColor();
		pointColor.setX(100);
		pointColor.setY(200);
		pointColor.setRgb(new Rgb(255,128,100));
//		PointColor pointColor = new PointColor(100,200,new Rgb(255,128,100));
		
		GraphicsCardMain gCardMain = new GraphicsCardMain();
		gCardMain.operatingSystemWrite(amdRadeon, pointColor);
		
		System.out.println();
		
		gCardMain.operatingSystemWrite(nvidiaGeForce, pointColor);	
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

** 예제 1123 (다형성) **

class Parent4{
	int x = 100;
	
	void method() {
		System.out.println("Parent4 method()...");
	}
}

class Child4 extends Parent4{
	int x = 200;
	
	void method() {
		System.out.println("x = " + x);
		System.out.println("super.x = " + super.x);
		System.out.println("this.x = " + this.x);
	}
}

public class MySample1123 {

	public static void main(String[] args) {
		// 다형선 - 참조형변수와 인스턴스 연결
		// 다형성 _ 부모타입의 참조변수로 자식의 객체를 만든다.
		Parent4 p  = new Child4();
		Child4 c = new Child4();
		
		System.out.println("p.x = "+ p.x);	//인스턴스 변수는 참조(잠조형변수=부모의 인스턴스변수)하는 값이 찍힌다. p.x = 200
		p.method();							
		
		System.out.println("c.x = " + c.x);
		c.method();
		
		//Parent p = new Child();
		
		//인스턴스 변수
		//부모에게 있고 자식에도 있으면 -> 부모꺼 실행
		//부모에게 있고 자식에게 없으면 -> 부모꺼 실행
		//부모에는 없고 자식에게 있으면 -> 오류2
		
		//메소드
		//부모에게 있고 자식에도 있으면 -> 자식꺼 실행 (메소드 오버라이딩)
		//부모에게 있고 자식에게 없으면 -> 부모꺼 실행
		//부모에는 없고 자식에게 있으면 -> 오류2
	}
}

** 예제 1123_2 (다형성) **

class Product2{
	int price;		//제품가격
	int bonusPoint;		//제품구매시 제공 보너스 점수
	
	Product2(int price){
		this.price = price;
		bonusPoint = (int)(price / 10.0);		//제품가격의 10퍼센트 적용
		
	}
}

class Tv3 extends Product2{
	Tv3(){
		super(900);
	}
	
	public String toString() {
		return "Tv";
	}
}

class Computer2 extends Product2{
	Computer2(){
		super(500);
	}
	
	public String toString() {
		return "Computer";
	}
}

class Buyer{
	int money = 10000;		//보유금액
	int bonusPoint = 0;		//보유보너스
	
	void buy(Product2 p) {	//매개변수의 다형성
		if (money < p.price) {		//보유금액보다 사려는 가격비 비싼경우 못사게 처리
			System.out.println("잔액 부족으로 물건을 살 수 없습니다.");
			return;	//프로그램 끝
		}
		
		money -= p.price;		//this.money = this.money - p.price;
		bonusPoint += p.bonusPoint;		//this.bonusPoint = this.bonusPoint + p.bonusPoint
		System.out.println(p + "을(를) 구매하셨습니다.");
	}
	
}



public class MySample1123_2 {

	public static void main(String[] args) {
		// 다형성 - 매개변수의 다형성
		
		Buyer b = new Buyer();
		
		System.out.println("현재 보유중인 현금은 " + b.money + "만원 입니다.");
		
		Product2 p = new Tv3();		//Tv3 p = new Tv3(); 으로 해도 결과는 같음 (Buyer 클래스 buy메서드에 매개변수가 매개변수가 다형성)
		b.buy(p);			//b.buy(new Tv3()); -> main()메서드에서 구매제품에 대한 정보를 알 수 없음.
		
		System.out.println("현재 구매한 가격은 " + p.price + "입니다.");
		System.out.println("현재 남은 돈은 " + b.money + "만원 입니다.");
		System.out.println("현재 보유중인 보너스 점수는 " + b.bonusPoint + "점 입니다.");
		
		System.out.println("\n");
		
		Product2 p2 = new Computer2();
		b.buy(p2);
		
		System.out.println("현재 구매한 가격은 " + p2.price + "입니다.");
		System.out.println("현재 남은 돈은 " + b.money + "만원 입니다.");
		System.out.println("현재 보유중인 보너스 점수는 " + b.bonusPoint + "점 입니다.");		
		
	}

}

** 예제 1123_3 (다형성 - 객체를 배열로) **

class Product3{
	int price;
	int bonusPoint;
	
	Product3(int price){
		this.price = price;
		this.bonusPoint = (int)(price*0.1);
	}
}

class Tv4 extends Product3{
	Tv4(){
		super(100);
	}
	
	public String toString() {
		return "Tv";
	}
}

class Computer3 extends Product3{
	Computer3(){
		super(300);
	}
	
	public String toString() {
		return "컴퓨터";
	}
}

class Audio extends Product3{
	Audio(){
		super(50);
	}
	
	public String toString() {
		return "오디오";
	}
}

class Buyer2{
	int money = 1000;
	int bonusPoint = 0;
	Product3[] item = new Product3[10];
	int cnt = 0;							//배열에 사용될 카운트
	
	void buy(Product3 p) {
		if(money < p.price) {
			System.out.println("잔액 부족으로 물건을 살 수 없습니다.");
			return;
		}
		
		money -= p.price;
		bonusPoint += p.bonusPoint;
		item[cnt++] = p;	//p - 객체의 시작 주소값
		
		System.out.println(p + "을(를) 구매하셨습니다.");		//각 클래스에 toString 오버라이딩 메서드 호출
		
		int i; 
		for(i = 0 ; i < item.length ; i++) {
			System.out.println("item[" + i + "] : " + item[i]);
		}
	}
	
	void summary() {
		int sum = 0;			//구입물품 가격 합계
		String itemList = "";	//구입물품 목록
		int i;
		
		//구입한 물품 총 가격과 목록
		for(i = 0 ; i < item.length ; i++) {
			if(item[i] == null)
				break;
			
			sum += item[i].price;
			
			itemList += item[i].toString() + ", ";
		}
		
		System.out.println("구입하신 물품의 총 금액은 " + sum + "만원 입니다.");
		System.out.println("구입하신 제품은 "+ itemList + "입니다.");
		System.out.println("구입하신 제품의 총 보너스 점수는 " + bonusPoint + "점 입니다.");
	}
}

public class MySample1123_3 {

	public static void main(String[] args) {
		
		// 다형성 - 객체를 배열로
		
		Buyer2 b = new Buyer2();
		
		b.buy(new Tv4());
		b.buy(new Computer3());
		b.buy(new Audio());
		b.summary();
	}
}



 

** Vector 클래스 **

- 자바의 배열은 고정 길이를 사용함. 즉, 배열이 한번 생성되면 배열의 길이를 증가하거나 감소 할 수 없다는 단점이 있음. (배열복사 말고)

- Vector클래스는 가변길이의 배열이라고 할 수 있음. (내부적으로 배열복사)

- 즉 Vector클래스는 객체에 대한 참조값을 저장하는 배열이므로 다양한 객체들이 하나의 Vectoer에 저장될 수 있고 길이도 필요에 따라 증감할 수 있다는 점이 배열과 다른 점이다.

 

.Vector 클래스의 생성자

Vector 클래스의 생성자 설 명
Vector() 10개의 데이터를 저장할 수 있는 길이의 객체를 생성한다.
저장공간이 부족한 경우 10개씩 증가한다.
Vector(int size) size 개의 데이터를 저장할 수 있는 길이의 객체를 생성한다.
저장공간이 부족할 경우 size개씩 증가한다.
Vector(int size, int incr) size 개의 데이터를 저장할 수 있는 길이의 객체를 생성한다.
저장공간이 부족한 경우 incr개씩 증가한다.

 

. Vetor 클래스의 주요 메서드

메서드 / 생성자 설 명
Vector() 10개의 객체를 저장할 수 있는 Vector인스턴스를 생성한다.
10개이상의 인스턴스가 저장되면, 자동적으로 크기가 증가된다.
boolean add(Object o) Vector에 객체를 추가한다. 추가에 성공하면 결과값으로 true, 실패하면 false를 반환한다.
boolean remove(Object o) Vector에 객체를 제거한다. 제거에 성공하면 결과값으로 true, 실패하면 false를 반환한다.
boolean isEmpty(Object o) Vector가 비어있는지 검사한다. 비어있으면 결과값으로 true, 비어있지 않으면 false를 반환한다.
boolean get(int index) 저장된 위지(index)의 객체를 반환한다. 반환타입이 Object타입이므로 적절한 타입으로의 형변환이 필요하다.
int size() Vetor에 저장된 객체의 개수를 반환한다.

** 예제 1123_4 **

import java.util.Vector;

class Buyer3{
	int money = 1000;
	int bonusPoint = 0;
	
	Vector item = new Vector();
	
	void buy(Product3 p) {
		System.out.println("vector size() : " + item.size());
		if(money < p.price) {
			System.out.println("잔액이 부족하여 물건을 살 수 없습니다.");
			return;
		}
		
		money -= p.price;
		bonusPoint += p.bonusPoint;
		item.add(p);
		
		System.out.println(p + "을(를) 구매하셨습니다.");
	}
	
	void summary() {
		int sum = 0;
		String itemList = "";
		int i;
		Product3 p = null;
		
		if(item.isEmpty() == true) {		//if(item.size()==0)
			System.out.println("구입한 물건이 없습니다.");
			return;
		}
		
		for(i = 0 ; i < item.size() ; i++) {
//			p = (Product3)item.get(i);				//p == item.get(i) ???
			
			sum += p.price;
			itemList += (i == 0) ? p : ("," + p) ;						//p + ", ";
		}
		
		System.out.println("구입한 총 금액 " + sum + "만원 입니다.");
		System.out.println("구입한 물품은 " + itemList + "입니다.");
		
	}
	
	//환불
	void refund(Product3 p) {
		if(item.remove(p)) {
			money += p.price;
			bonusPoint -= p.bonusPoint;
			
			System.out.println(p + "을(를) 반풍하셨습니다.");
		}
		
		else {
			System.out.println("해당제품이 없습니다.");
		}
		
		
	}
	
}

public class MySample1123_4 {

	public static void main(String[] args) {
		// Vector() 클래스
		
		Buyer3 b = new Buyer3();
		Tv4 t = new Tv4();
		Computer3 com = new Computer3();
		Audio audio = new Audio();
		
		b.buy(t);
		b.buy(com);
		b.buy(audio);
		b.summary();
		
		System.out.println("\n");
		
		//환불
		b.refund(com);
		b.summary();
		
		b.refund(com);			//이미 삭제된 상품이므로 vector에 없음. 오류발생
		
		
	}

}



** 추상클래스 (abstract class) **

- 하나 이상의 추상 메소드를 포함하는 클래스를 의미함

- 추상메소드 : 자식클래스에서 반드시 오버라이딩 해야만 사용할 수 있는 메소드

- 반드시 사용되어야 하는 메소드를 추상클레스에 추상메소드로 선언을 하면, 이 클래스를 상속받는 모든 클래스에서 이 추상 메소드를 반드시 재정의 해야함

 

abstract class 클래스 이름 {

                ...

               abstract 반환타입 메소드이름();

                ...

}

 

- 추상클래스는 추상메소드를 포함하고 있다는 점 이외에는 일반 클래스와 모든점이 같다. 즉 생성자와 변수, 일반 메소드도 포함 할 수 있음.


** 예제 abs패키지 _ 1123_5 **

package abs;

abstract class Animal{
	
	int num;
	
	void numChk() {
		System.out.println("num : " + num);
	}
	
	abstract void cry();	//추상클래스에는 추상메서드가 있어야한다.
}

class Cat extends Animal{
	void cry() {			//추상클래스에 있는 추상메소드 오버라이딩 한 것. but 상속받는 클래스에서 오버라이딩 할 때는 abstarct 쓰지 않는다.
		System.out.println("야오야옹");
	}
}

class Dog extends Animal{
	void cry() {
		System.out.println("멍멍....");
	}
}



public class MySample11223_5 {

	public static void main(String[] args) {
		
		// 추상클래스
		//Animal a = new Animal();		//추상클래스는 인스턴스를 생성할 수 없음.(객체생성 불가)
		Cat c = new Cat();				//Animal c = new Cat();		가능
		Dog d = new Dog();				//Animal d = new Dog();		가능
		
		c.cry();
		d.cry();
		
	}

}

** 예제 abs패키지 _ 1123_6 (포켓몬) **

package abs;

abstract class Pokemon
{
	private String name;
	
//	Pokemon(){
//		
//	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	abstract void attack();			//공격
	abstract void sound();			//소리
	
	
	
}

class Pikachu extends Pokemon{
	
	Pikachu(){
		super.setName("피카츄");
	}
	
	void attack() {
		System.out.println("전기공격");
	}
	void sound() {
		System.out.println("피카피카");
	}
	
	
}

class Spuirtle extends Pokemon{
	
	Spuirtle(){
		setName("꼬부기");
	}
	
	void attack() {
		System.out.println("물뿌리기 공격");
	}
	void sound() {
		System.out.println("꼬북꼬북");
	}
	
	
}

public class MySample1123_6 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//추상클래스
		
		Pikachu p1 = new Pikachu();
		System.out.println("포켓몬 이름은 " + p1.getName());
		p1.attack();
		p1.sound();
		
		Spuirtle s1 = new Spuirtle();
		System.out.println("포켓몬 이름은 " + s1.getName());
		s1.attack();
		s1.sound();

	}

}

 


** abs2 패키지 _ 추상클래스 상속 _ Animal 클래스 / Bird 클래스 / Cat 클래스 / Dog 클래스 **

package abs2;
public abstract class Animal {
	
	//동물이름
	protected String name;		//private String name;
	
	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	//어떻게 우는지
	public abstract String getCry();
	
	//어떻게 움직이는지
	public abstract String getMove();
	
	//무엇을 먹는지
	public abstract String getFood();
	
	//출력
	public abstract void print();	
}

* class Bird *

package abs2;
public class Bird extends Animal{
	
	//생성자는 이름(name)을 매개변수로 하는 것과 매개변수가 4개로 생성자를 각각 정의함.
	//이름 : name, 울음 : 짹짹, 움직임 : 날아다닌다, 음식 : 벌레
	private String cry;
	private String move;
	private String food;
	
	Bird(String name){
		this(name, "짹짹", "날아다닌다", "애벌레");
	}
	
	Bird(String name, String cry, String move, String food){
		//super();			//생략되어있다.
		setName(name);		//super. 생략
		setCry(cry);
		setMove(cry);
		setFood(food);
	}
	
	public String getCry() {
		return this.cry;
	}
	public void setCry(String cry) {
		this.cry = cry;
	}
	
	public String getMove() {
		return this.move;
	}
	public void setMove(String move) {
		this.move = move;
	}
	
	public String getFood() {
		return this.food;
	}
	public void setFood(String food) {
		this.food = food;
	}
	
	public void print() {
		System.out.println("Bird [name : "+ getName() + ", cry : " + getCry() + ", move : " + getMove() + ", food : " + getFood() + "]");
	}
}

* class Cat *

package abs2;
public class Cat extends Animal{
	
	private String cry;
	private String move;
	private String food;
	
	Cat(String name){
		this(name, "야옹", "걸어댜녀요", "생선");
	}
	
	Cat(String name, String cry, String move, String food){
		setName(name);
		setCry(cry);
		setMove(move);
		setFood(food);
	}
	
	public String getCry() {
		return this.cry;
	}
	public void setCry(String cry) {
		this.cry = cry;
	}
	
	public String getMove() {
		return this.move;
	}
	public void setMove(String move) {
		this.move = move;
	}
	
	public String getFood() {
		return this.food;
	}
	public void setFood(String food) {
		this.food = food;
	}
	
	public void print() {
		System.out.println("Cat [name : " + getName() + ", cry : " + getCry() + ", move : " + getMove() + ", food : " + getFood() + "]");
	}
}

* class Dog *

package abs2;
public class Dog extends Animal {
	
	//멍멍, 촐랑촐랑 뛴다. 사료
	private String cry;
	private String move;
	private String food;
	
	Dog(String name){
		this(name, "멍멍", "촐랑촐랑 뛴다", "사료");
	}
	
	Dog(String name, String cry, String move, String food){
		setName(name);		//super.name = name;
		setCry(cry);
		setMove(move);
		setFood(food);
	}
	
	public String getCry() {
		return this.cry;
	}
	public void setCry(String cry) {
		this.cry = cry;
	}
	
	public String getMove() {
		return this.move;
	}
	public void setMove(String move) {
		this.move = move;
	}
	
	public String getFood() {
		return this.food;
	}
	public void setFood(String food) {
		this.food = food;
	}
	
	public void print() {
		System.out.println("Dog [name : " + getName() + ", cry : " + getCry() + ", move : " + getMove() + ", food : " + getFood() + "]");
	}
}

package abs2;

public class AnimalMain {
	public static void main(String[] args) {
		
		// 추상클래스 메인
		
		Dog dog = new Dog("재롱이");
		Cat cat = new Cat("나비");
		Bird bird = new Bird("짹짹이");
		
		cat.print();
		System.out.println();
		dog.print();
		System.out.println();
		bird.print();
		System.out.println();
		
		cat.setCry("어흥");
		cat.print();
		
		System.out.println();
		
		bird.setMove("펄럭펄럭");
		bird.print();
		
		System.out.println();
		
		dog.setFood("건조 닭고기");
		dog.print();	
	}
}

** 실습 abs1 패키지 **

/*
 *추상클래스
 *문제)Animal클래스를 추상클래스로 정의하고 이름(name), 나이(age) 변수를 정의하고 생성자(매개변수2개)를 통해 값 저장
 *   이동하는 메서드(move)로 먹는 메서드(eat)로 정의하여 이동은 "이동한다", 먹는것은 "먹는다"로 출력함.
 *   자식 클래스(Dog, Cat)에서 반드시 재정의 하도록 bark() 메서드로 짖는걸 구현함.
 *출력예)이동한다.
 * 멍멍
 * 먹는다.
 *
 * 이동한다.
 * 야옹 
 * 먹는다.
 */

 

 

 

 

 

 

 

 

** 문법 **

trim() : 문자열의 맨앞과 맨 뒤 공백만 제거
replace(" ","") : 문자열에서 첫번째 인수를 찾아 두번쨰 인수로 변경
replaceAll(" ", "") : 문자열에서 첫번째인수를 찾아 두번째 인수로 변경

public class MyProject1121_7 {

	public static void main(String[] args) {
		
		//접근제어자
		
		//******************************************************************************
		/* 문법
		 trim() : 문자열의 맨앞과 맨 뒤 공백만 제거
		 replace(" ","") : 문자열에서 첫번째 인수를 찾아 두번쨰 인수로 변경
		 replaceAll(" ", "") : 문자열에서 첫번째인수를 찾아 두번째 인수로 변경
		 */
		
		String tmp = "  홍 길동   ";
		System.out.println("trim() : [" + tmp.trim() + "]");
		System.out.println("replace() : [" + tmp.replace(" ", "") + "]");
		System.out.println("replace() : [" + tmp.replaceAll(" ", "홍") + "]");
		
		//******************************************************************************
        
	}
}

** 실습 1122 (접근제어자 + 오버라이딩)**

/* 접근제어자, 오버라이딩
 *출력예)좋은 아침입니다. 오전에는 맑음 입니다.
 *      즐거운 점심입니다. 점심에는 흐림입니다.
 *  행복한 오후되세요. 오후에는 비가 내리겠습니다.
 *단, greeting메서드를 이용함
 */

class Today{	//extends Object 생략
	private String weather;
	
	public String getWeather() {
		return this.weather;
	}
	public void setWeather(String weather) {
		this.weather = weather;
	}
	
	void greeting() {
		System.out.println("즐거운 하루 되세요.");
	}
	
//	//자식클래스 생성자에 super(weather); 사용할 경우
//	Today(String weather){
//		setWeather(weather);
//	}
}


class Morning extends Today{
		
	Morning(String weather){
		//super();		//생략되어있다.
		setWeather(weather);	//super. 생략됨 (Morning 클래스에 setWeather 메서드가 없기때문)
//		//super(weather);
	}
	
	void greeting() {
		System.out.println("좋은 아침입니다. 오전에는 " + super.getWeather() + "입니다.");
		//super. 생략가능 (Morning 클래스에 setWeather 메서드가 없기때문)
	}
}


class Lunch extends Today{
	
	Lunch(String weather){
		setWeather(weather);
	}
	
	void greeting() {
		System.out.println("즐거운 점심 입니다. 점심에는 " + getWeather() + "입니다.");
	}
}


class Dinner extends Today{
	
	Dinner(String weather){
		super.setWeather(weather);
	}
	
	void greeting() {
		System.out.println("행복한 오후되세요. 오후에는 " + getWeather() + "가 내리겠습니다.");
	}
}

public class MySample1122 {

	public static void main(String[] args) {
		
		//상속 + 오버라이딩
		
		Morning m = new Morning("맑음");
		Lunch l = new Lunch("흐림");
		Dinner d = new Dinner("비");
		
		m.greeting();
		l.greeting();
		d.greeting();
	}
}

** 실습 1122_2 (오버라이딩 + 접근제어자) **

class Car3{
	private int door;
	private String gearType;
	private String color;
	
	Car3(String color){
		//setColor(color);
		//setGearType("auto");
		//setDoor(4);
		this(color, "auto", 4);		//this. 같은 클래스 내에있는 타입갯수와 종류에 맞는 생성자 불러옴
	}
	Car3(String color, String gearType){
		//setColor(color);
		//setGearType(gearType);
		//setDoor(4);
		this(color, gearType, 4);
	}
	Car3(String color, String gearType, int door){
		setColor(color);
		setGearType(gearType);
		setDoor(door);
	}
	
	
	public int getDoor() {
		return this.door;
	}
	public void setDoor(int door) {
		this.door = door;
	}
	
	public String getGearType() {
		return this.gearType;
	}
	public void setGearType(String gearType) {
		this.gearType = gearType;
	}
	
	public String getColor() {
		return this.color;
	}
	public void setColor(String color) {
		this.color = color;
	}

}


class SportsCar extends Car3{
	int speedLimit;			//제한속도

	SportsCar(String color){
		super(color);		
		//setColor(color);	//super(); 생략되어있어서 오류남
		this.speedLimit = 200;
	}
	
	SportsCar(String color, int speedLimit){
		super(color);		
		this.speedLimit = speedLimit;
	}
	
	SportsCar(String color, String gearType){
		super(color, gearType);		
		this.speedLimit = 200;
	}
	
	SportsCar(String color, String gearType, int speedLimit){
		super(color, gearType);		
		this.speedLimit = speedLimit;
	}
	
	SportsCar(String color, String gearType, int door, int speedLimit){
		super(color, gearType, door);
		this.speedLimit = speedLimit;
	}
	
	public String toString() {
		
		return "차량의 색은 "+ getColor() +"이고, " + getGearType() + "이며, 문의 개수는 "  + getDoor() + "개이며," + " 제한 속도는 " + speedLimit + " 입니다.";
	}
	
}

public class MySample1122_2 {

	public static void main(String[] args) {
		
		/*
		 실행결과)차량의 색은 red이고, auto이며, 문의 개수는 4개이며,
		 		 제한 속도는 330 입니다.
		 (단, 차량 색은 반드시 입력받고, 제한속도가 없을 경우 200, 기어타입이 없을 경우 auto로 정의함)
		 	  문 개수가 없을 경우 기본 4개로 정의함.
		 클래스와 변수는 세팅되있는것만 사용한다.
		 단 정수가 하나만들어온 경우 speedLimit으로 여긴다.
		 */
		
		SportsCar cs = new SportsCar("red", 330);
		
		System.out.println(cs.toString());		//.toString 생략되어있음
		
	}

}



** 다형성(polymorphism) **

하나의 객체가 여러가지 타입을 가질 수 있는 것을 의미.

부모 클래스 타입의 참조 변수로 자식클래스 타입의 인스턴스를 참조 할 수 있도록 구현.

 

참조 변수의 다형성

class Parent{...}

class Chlid extends Parent{...}

...

Parent pa = new Parent();   // 허용

chlid ch = new Child();   // 허용

Parent pc = new Chlid();   // 허용

Child cp = new Parent();   // 오류 발생

//상속을 통해 확장된 수 있으나 축소될수는 없음. 자식클래스에서 사용할 수 있는 멤버(인스턴스변수, 인스턴스 메소드...)의 개수가 언제나 부모 클래스와 같거나 많게됨

 

 

instanceof   :  연산자 /  참조변수가 참조하고 있는 인스턴스 실제 타입 확인

문법)참조변수 instanceof 클래스이름 -> true, false 리턴

 

다형성에서 어떠한 변수와 메소드를 사용할 것인가?

* 인스턴스 변수

// 부모에게 있고 자식에도 있으면 -> 부모꺼 실행
// 부모에게 있고 자식에게 없으면 -> 부모꺼 실행
// 부모에는 없고 자식에게 있으면 -> 오류2

* 메소드
// 부모에게 있고 자식에도 있으면 -> 자식꺼 실행 (메소드 오버라이딩)
// 부모에게 있고 자식에게 없으면 -> 부모꺼 실행
// 부모에는 없고 자식에게 있으면 -> 오류2

** 1122_3 예제 (다형성) **

class A{
	void methodA() {
		System.out.println("methodA()...");
	}
}

class B extends A{
	void methodB() {
		System.out.println("methodB()...");
	}
}

public class MySample1122_3 {

	public static void main(String[] args) {
		
		A obj = new B();
		obj.methodA();		//가능
//		obj.methodB();		//불가능
		
		B obj2 = new B();
		obj.methodA();		//가능
		obj2.methodB();		//가능
		
	}

}

** 예제 1122_4 (다형성) **

class Car4{
	String color;
	int door;
	
	void drive() {
		System.out.println("drive()...Car4");
	}
	
	void stop() {
		System.out.println("stop()...Car4");
	}
}

class FireEngine extends Car4{
	void water() {
		System.out.println("water()...FireEngine");
	}
}


public class MySample1122_4 {

	public static void main(String[] args) {
		
		// 다형성
		
		
//		Car4 c = null;
//		FireEngine f = new FireEngine();
//		FireEngine f2 = null;
//		
//		f.water();
//		c = f;			//다형성 => Car4 c = new FireEngine(); 과 같다.
//						//내부적으로 형변환이 발생했음.(up-casting)
//		
//		//c.water();		//불가능(부모형 참조변수로 자식객체를 바라볼수 있으나 자식객체에 메서드는 사용할 수 없음)
//		
//		f2 = (FireEngine)c;		//안되지만 (FireEngine)으로 강제 형변환해서 사용가능
//								//down-casting이므로 강제 형변환 꼭해야함.
//		f2.water();
		
		
		//불가능한예제
		
		Car4 c = new Car4();		//= new FireEngine();로 변경하면 1.싫애시에도오류안남
//		Car4 c = new FireEngine();
		Car4 c2 = null;
		FireEngine f = null;
		Car4 c3 = new FireEngine();
		
		c.drive();
		//f = (FireEngine)c;			//f = c; 는 불가능 하나 형변환을 통해서 가능
									//컴파일은 가능하나 시행시 오류 발생
		
		f.drive();					// 실행시오류 
		
		c2 = f;						//up-casting
		//c2.water();				//불가능 : c2 참조변수는 클래스 타입이 Sard4이고 water()a메서드는 			
		c2.drive();
		c2.stop();					// 		  FireEngine클래스의 메서드이기 떄문에 호출불가
		
	}

}

** 예제 1122_6 (다형성) **

class Animal3{
	void breath() {
		System.out.println("숨쉬기");
	}
	
	public String toString() {
		return "몰라";
	}
}

class Lion3 extends Animal3{
	public String toString() {
		return "사자";
	}
}

class Rabbit extends Animal3{
	public String toString() {
		return "토끼";
	}
}

class Monkey extends Animal3{
	public String toString() {
		return "원숭이";
	}
	public void printA() {
		System.out.println("printA()...");
	}
}

class ZooKeeper{
	
//	void feed(Lion3 lion) {
//		System.out.println(lion + "에게 먹이주기...");
//	}
//	
//	void feed(Rabbit rabbit) {
//		System.out.println(rabbit + "에게 먹이주기...");
//	}
//	
//	void feed(Monkey monkey) {
//		System.out.println(monkey + "에게 먹이주기...");
//	}
	
	void feed(Animal3 animal) {
		System.out.println(animal + "에게 먹이주기...");
	}
	
}


public class MySample1122_5 {

	public static void main(String[] args) {
		
		// 다형성
		
		ZooKeeper j = new ZooKeeper();
//		
//		Lion3 lion1 = new Lion3();
//		j.feed(lion1);
//		
//		Rabbit rabbit = new Rabbit();
//		j.feed(rabbit);
//		
//		Monkey monkey = new Monkey();
//		j.feed(monkey);
		
		Animal3 lion1 = new Lion3();	//객체생성은 Lion3, 바라보는관점은 Animal3 -> Animal3에 있는 것들을 사용할 수 있음
		j.feed(lion1);
		
		Animal3 rabbit = new Rabbit();
		j.feed(rabbit);
		
		Animal3 monkey = new Monkey();
		j.feed(monkey);
		
		j.feed(new Animal3());		// Animal3 animal = new Monkey(); //다시보기!!!!
		
		monkey.printA();			// 오류 : monkey참조변수는 Animal3클래스의 참조변수이므로
									//		 Monkey() 클래스에 있는 printA()메서드 접근 불가능
	}
}

** 예제 1122_6 (다형성_ 연산자 instanceof) **

class Parent3{
}

class Child3 extends Parent3{
}

class Brother extends Parent3{
}

public class MySample1122_6 {

	public static void main(String[] args) {
		
		// 다형성 (instanceof 연산자)
		
		Parent3 p = new Parent3();
		
		System.out.println(p instanceof Object);	// true
		System.out.println(p instanceof Parent3);	// true
		System.out.println(p instanceof Child3);	// false
		
		Parent3 p2 = new Child3();
		
		System.out.println(p2 instanceof Object);	// true
		System.out.println(p2 instanceof Parent3);	// true
		System.out.println(p2 instanceof Child3);	// true
		
		//부모에게 있고 자식에도 있으면 -> 자식꺼 실행
		//부모에게 있고 자식에게 없으면 -> 부모꺼 실행
		//부모에는 없고 자식에게 있으면 -> 오류

	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

** 실습 1121 (상속) **

/* 1
 문제)친구정보를 기록할 MyFriendInfo 클래스를 상세정보를 기록할 MyFriendDetailInfo클레스에 상속하고
   이름, 나이는 MyFriendInfo 클래스에서 주소와 전화번호는 MyFriendDetailInfo 클래스에서 입력할 수 있도록 구성함.
 출력예)이름 : 이순신
    나이 : 100
    주소 : 성균관
    전화 : 010-1111-2222
    단, 각 클래스에서 출력하는 메서드가 존재하며, main 메서드에서는 생성자와 출력메서드 한번만 호출(자식클래스)하여 적용함.(메인에는 두줄)
      입력값은 생성자를통해서 하드코딩하여 저장함. new 클래스( "이순신", 100, "성균관 ', "010-1111-2222")
 */

class MyFriendInfo{
	String name;
	int age;
	
	MyFriendInfo(String name, int age){
		this.name = name;
		this.age= age;
	}
	
	void printMyFriendInfo(){
		System.out.println("이름 : " + name);
		System.out.println("나이 : " + age);
	}
	
}

class MyFriendDetailInfo extends MyFriendInfo{
	String add;
	String num;
	
	MyFriendDetailInfo(String name, int age, String add, String num){
		super(name, age);
//		super.name = name;		//이렇게 쓰지 않는 이유 :  나중에 배울 오버라이딩 배우면 앎
//		super.age = age;		//이렇게 쓰려면 위의 MyFriendInfo 메서드 없어야 함.
		this.add = add;
		this.num = num;		
	}
	
	void printMyFriendDetailInfo() {
		super.printMyFriendInfo();			//여기서는 super. 생략되도 됨 (이유 : 같은 메소드명이 자식에 없기때문임)
		System.out.println("주소 : " + add);
		System.out.println("전화 : " + num);
	}
	
}

public class MySample1121 {

	public static void main(String[] args) {
		
		//상속
		
		MyFriendDetailInfo mfdi = new MyFriendDetailInfo("이순신", 100, "성균관	", "010-1111-2222");
		mfdi.printMyFriendDetailInfo();

	}

}

class MyFriendInfo
{
	MyFriendInof(){
    }
}


class MyFriednDetailInfo extends MyFriendInfo
{
	MyFriednDetailInfo(){
    	super();
    }
}

//class MyFriendInfo 와 class MyFriednDetailInfo가 생성자 없이 만들어지면 
//JVM이 매개변수없는 생성자를 하나씩 만들어준다. (코드에 보이지 않아도 존재한다)
//-> but 생성자를 만들어 놓으면 JVM이 매개변수없는 생성자를 생성해주지 않는다.
//상속 받는 자식클래스의 매개변수 없는 생성자에는 super();이 생략되어있다.

 


생성자 or 매서드 에서 변수의 순위 

지역변수 -> 인스턴스변수 -> 부모변수

생성자 or 메서드에서 변수 쓰임

지역변수 : 변수명만 쓴다.

인스턴스변수 : this.변수명

부모변수 : super.변수명


// 모든 클래스는 object.class를 상속받게 되어있다.(object 는 상속받는 클래스의 최상위 클래스라고 생각하면 된다.) 

// JDK가 object.class 를 상속받게 해둔다.


** 예제 1121_2 (상속) **

// 상속
/*
 실행결과)kind : SPACE, number : 1
      kind : HEART, number : 7 (실행시 마다 변경)
 */

import java.util.Random;

class Card2{
	static final int KIND_MAX = 4;			//카드무늬수 (클래스 상수로 정의)
	static final int NUM_MAX =13;			//무니별 카드수
	
	static final int SPADE = 4;
	static final int DIAMOND = 3;
	static final int HEART = 2;
	static final int  CLOVER = 1;
	
	int kind;
	int number;
	
	Card2(){
		this(SPADE, 1);
	}
	
	Card2(int kind, int number){
		this.kind = kind;
		this.number = number;
	}
	
	public String toString() {
		
		String[] kinds = {"", "CLOVER", "HEART", "DIAMOND", "SPADE"};
		String numbers = "0123456789XJQK";		//숫자 10은 X로 사용
		
		return "kind : " + kinds[this.kind] + ", number : " + numbers.charAt(this.number);	//charAt this.number 의 위치값만 뽑아옴
	}
}

class Deck{
		final int CARD_NUM = 52;	//카드개수
		Card2[] cardArr = new Card2[CARD_NUM];
		
		Deck() {
			int i = 0, k, n;
			
			for(k = Card2.KIND_MAX ; k > 0 ; k--) {		//4
				//KIND_MAX 4부터 시작(4~1)
				for(n = 0 ; n < Card2.NUM_MAX ; n++) {	//13
					//NUM_MAX = 13 (1~12)
					System.out.println("Deck()생성자 : i = " + i + ", k = " + k + ", n = " + n);
					cardArr[i++] = new Card2(k, n+1);
				}
			}
		}
		
		//지정된 위치(index)에 있는 카드 하나를 꺼내 반환함.
		Card2 pick(int index) {		//리턴타입 Card 객체
			return cardArr[index];
		}
		
		Card2 pick() {		//메소드 오버로딩
			int index = (int)Math.random() * 52;	//0~51사이값, 오류뜨면 Math앞에 java.lang. 써준다.
			return pick(index);
		}
		
		//카드 순서 섞기
		void shuffle() {
			int i, r;
			Card2 tmp;
			
			for(i = 0 ; i < cardArr.length ; i++) {
				r = (int)(java.lang.Math.random() * CARD_NUM);		//0~51사이
			tmp = cardArr[i];
			cardArr[i] = cardArr[r];
			cardArr[r] = tmp;
			}
		}
		
		void printArr() {
			int i;
			
			for(i = 0 ; i < cardArr.length ; i++)
			{
				System.out.println("cardArr[" + i + "] : " + cardArr[i]); 
			}
		}
}


public class MySample1121_2 {

	public static void main(String[] args) {
		// 상속
		/*
		 실행결과)kind : SPACE, number : 1
		 	    kind : HEART, number : 7 (실행시 마다 변경)
		 */
		
		Deck d = new Deck();
		Card2 c = d.pick(0);		//카드를 섞기 전에 제일 위 카드 뽑기
		System.out.println("before : " + c.toString());
		System.out.println("before : " + c);	//윗줄과 결과 같다.
		
		System.out.println("\n");
		
		d.printArr();
		
		d.shuffle();	//카드 섞기
		c = d.pick(0);	//카드 섞고나서 제일 위 카드 뽑기
		System.out.println("after : " + c.toString());
		
		System.out.println("\n");
		
		d.printArr();
	}

}

** 오버라이딩 (overriding) **

상속관계에서 부모 클래스로부터 상속받은 메서드의 내용(구현부)을 자식클래스에서 변경하는 것

자손 클래스에서 오버라이딩하는 메서드는 조상 클래스의 메서드와 선언부가 같아야한다.

-.이름(메소드명)이 같아야한다.

-.매개변수가 같아야 한다.

-.반환타입이 같아야한다.

 


** 예제 1121_3 (오버라이딩) **

class Point2{
	int x;
	int y;
	
	String getLocation() {
		return "x : " + x + "y : " + y;
	}
}

class Point3D extends Point2{
	int z;
	
	String getLocation() {
		//return "x : " + x + ", y : " + y + ", z : " +z;
		//부모클래스의 getLocation()메서드 호출방법
				return super.getLocation() +", z : " + z;
		
	}
}

public class MySample1121_3 {

	public static void main(String[] args) {
		
		//오버라이딩
		Point3D p3 = new Point3D();
		
		p3.x = 10;
		p3.y = 20;
		p3.z = 30;
		
		System.out.println(p3.getLocation());
		
	}

}

 


** 예제 1121_4 (오버라이딩) **

class Parent{
	int x = 10;
}

class Child extends Parent{
	int x = 20;
	
	void methodA() {
		int x = 30;
		
		System.out.println("x : " + x);				//지역변수
		System.out.println("this.x : " + this.x);	//인스턴스 변수
		System.out.println("super.x : " + super.x);	//부모에 정의된 인스턴스 변수
		
		
	}
}

public class MySample1121_4 {

	public static void main(String[] args) {
		
		Child c = new Child();
		c.methodA();
	}

}

** 예제1121_5 (오버라이딩) **

class Point3{
	
	int x, y;
	
	Point3(){
		this(0,0);
	}
	
	Point3(int x, int y){
		this.x = x;
		this.y = y;
	}
	
	String getLocation() {
		return "x : " + x + ", y : " + y;
	}
}


class Point3D2 extends Point3{
	
	int z;
	
	Point3D2(){
		this(0, 0, 0);
	}
	
	Point3D2(int x, int y, int z){
		super(x, y);
		//super.x = x;
		//super.y = y;
		this.z = z;
	}
	
	String getLocation() {
		//return "x : " + x + ", y : " + y + ", z : " + z;
		return super.getLocation();
	}
}

public class MySample1121_5 {

	public static void main(String[] args) {
		
		//오버라이딩
		Point3D2 p3 = new Point3D2(1, 2 , 3);
		System.out.println(p3.getLocation());
		
		//getLocation()메서드를 Point3클래스 메서드를 호출하는 방법 2가지
		//첫번째
		Point3 p = new Point3(1, 2);
		System.out.println(p.getLocation());
		//두번째
		System.out.println(p3.getLocation());	//Point3D2의 getLocation()메서드를 return super.getLocation();로 바꾼다.
	}

}
class Clothes{
	void cutHeight() {
		System.out.println("높이 수선하였습니다.");
	}
	
	void cutWidth() {
		System.out.println("넓이를 수선하였습니다.");
	}
	
	void showPrice() {
		System.out.println("수선비용은 : 5000원");
	}
}

class Reform extends Clothes{
	void cutHeight() {
		System.out.println("높이를 다시 맞춰 수선하였습니다.");
	}
	
	void cutWidth() {
		System.out.println("넚이를 다시 맞춰 수선하였습니다.");
	}
	
}



public class MySample1121_5 {

	public static void main(String[] args) {
		
		//오버라이딩
		Clothes ct = new Clothes();
		Reform re = new Reform();
		
		ct.cutHeight();
		ct.cutWidth();
		ct.showPrice();
		
		re.cutHeight();
		re.cutWidth();
		re.showPrice();		//자식메소드를 통해 부모메소드를 불러옴
		
	}
}



** 접근 제어자 (access modifier) **

- 멤버 또는 클래스에 사용되어 해당하는 멤버 또는 클래스 외부에서 접근하지 못하도록 제한하는 역할

 

* 접근제어자의 종류

접근제어자 사용 가능 범위
private 같은 클래스 내에서만 접근 가능 / 접근제어자 가장 강함
default 같은 패키지 내에서만 접근 가능 (아무것도 쓰지 않으면 default)
protected 같은 패키지 내에서와 다른 패키지의 자손클래스에서 접근 가능
public 접근 제한 없음 / 접근제어자 가장 약함

- 위로 갈 수 록 접근제어가 강해진다.

 

cf) 패키지란? + 패키지 생성

- src 아래 (default package) 가 package이다.

- src 클릭후 new -> package 생성 또는 src 클릭후 new -> class 생성 (생성할 때 package명에 사용할 package명 입력하고 생성) 

 

* 대상에 따라 사용할 수 있는 접근 제어자

대상 사용가능한 접근 제어자
클래스 public, (default)
메서드 
멤버변수
public, protected, (default), private
지역변수 없음(메서드 안에 있기에 메서드 끝나면 끝남)

 

 

* 접근제어자 사용 이유

- 외부로부터 데이터 보호

- 내부적으로 사용되는 부분을 감추기 위해

 


** 예제 1121_6 (접근제어자) **

class Time{
	private int hour, minute, second;
	
	Time(int hour, int minute, int second){
		setHour(hour);			//this.hour = hour;
		setMinute(minute);		//this.minute = minute;
		setSecond(second);		//this.second = second;
	}
	
	public void errorPrint(String msg) {
		System.out.println("현재 오류는 " + msg + "입니다.");
	}
	
	public int getHour() {
		return this.hour;
	}
	
	public void setHour(int hour) {
		//시간 0 ~ 23시 사이 값만 허용
		if(hour < 0 || hour >23) {
			errorPrint("시간(0~23시 사이) 오류");
			return;		//이 아래로 실행하지 않고 중간에 나를 호출한 곳으로 다시 돌아가겠다는 의미
		}
		this.hour = hour;
	}
	
	public int getMinute() {
		return this.minute;
	}
	
	public void setMinute(int minute) {
		//분은 0~59분 사이 값만 허용.
		if(minute < 0 || minute > 59) {
			errorPrint("분(0~59분 사이) 오류");
			return;
		}
		this.minute = minute;
	}
	
	public int getSecond() {
		return this.second;
	}
	
	public void setSecond(int second) {
		//초는 0~59분 사이 값만 허용.
		if(second < 0 || second > 59) {
			errorPrint("초(0~59분 사이) 오류");
			return;
		}
		this.second = second;
	}
	
	public String toString() {
		return getHour() + ":" + getMinute() + ":" + getSecond();
	}
	
}

public class MySample1121_6 {

	public static void main(String[] args) {
		
		//접근제어자(private, (default), protected, public)
		Time t = new Time(16, 40, 31);
		
		System.out.println(t);
		
		t.setHour(t.getHour() + 1);		//t.hour = 17;
		
		System.out.println(t);			//t대신 t.toString 사용해도 같은의미다.

	}

}

** 실습 1121_7 (접근제어자) **

/*
문제)이름, 나이, 직업을 입력받아 입력받은 값을 화면에 출력하며, 이름에 "끝:이 입력되면 종료되는 프로그램 작성.
     단, 이름/나이/직업과 관련된 정보는 메서드를 사용하여 작성.(private)
       문자열비교 : 변수명.equals("끝")
       이름.나이.직업을 관리하는 클래스는 Person3 으로 하며, 예외처리 : 프로그램 종료여부와 정보출력(출력예) 메서드는 msgPrint()
입력예)이름은 > 홍길동
   나이는 > 23
   직업은 > 프로그래머
출력예)홍길동님의 나이는 23살이며, 직업은 프로그래머 입니다.

입력예)이름은 > 끝
   나이는 > 22
   직업은 > 백수
출력예)프로그램을 종료합니다.
 */

import java.util.Scanner;

/* 1
문제)이름, 나이, 직업을 입력받아 입력받은 값을 화면에 출력하며, 이름에 "끝:이 입력되면 종료되는 프로그램 작성.
     단, 이름/나이/직업과 관련된 정보는 메서드를 사용하여 작성.(private)
     	 문자열비교 : 변수명.equals("끝") //String 타입 비교 (문자열)
     	 이름.나이.직업을 관리하는 클래스는 Person3 으로 하며, 예외처리 : 프로그램 종료여부와 정보출력(출력예) 메서드는 msgPrint()
입력예)이름은 > 홍길동
	   나이는 > 23
	   직업은 > 프로그래머
출력예)홍길동님의 나이는 23살이며, 직업은 프로그래머 입니다.

입력예)이름은 > 끝
	   나이는 > 22
	   직업은 > 백수
출력예)프로그램을 종료합니다.
 */

class Person3{
	private String name, job;
	private int age;
	
	public String getName(){
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return this.age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	public String getJob(){
		return this.job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	
	
	//프로그램 종료여부와 출력
	public boolean msgPrint() {
		if(getName().equals("끝")) {
			System.out.println("프로그램 종료합니다.");
			return true;
		}
		else {
			System.out.println(getName() + "님의 나이는 " + getAge() + "살이며, 직업은 " + getJob()+ "입니다.");
			return false;
		}
	}
	
//	//위 boolean을 int로 사용할 경우 while(msgPrint()==1)로 쓴다.
//	public int msgPrint() {
//		if(getName().equals("끝")) {
//			System.out.println("프로그램 종료합니다.");
//			return 1;
//		}
//		else {
//			System.out.println(getName() + "님의 나이는 " + getAge() + "살이며, 직업은 " + getJob()+ "입니다.");
//			return 0;
//		}
//	}

}

public class MyProject1121_7 {

	public static void main(String[] args) {
		
		Scanner scn = new Scanner(System.in);
		
		//접근제어자
		
		Person3 p3 = new Person3();
		//Person3 p3 = null;	//다른방법1
		
		while(true) {
			
			//p3 = new Person3();	//다른방법1
			
			System.out.print("이름은 > ");
			p3.setName(scn.next());				//nextLine은 엔터키를 가지고 있기에 next()적용
			System.out.print("나이는 > ");
			p3.setAge(scn.nextInt());
			System.out.print("직업은 > ");
			p3.setJob(scn.next());
			
			if(p3.msgPrint()) {
				break;
			}
			
			// nextInt 와 next 는 공백도 자른다. nextLine은 엔터키를 가지고 있다.
			
		}
		
	}

}

 

 

 

 

 

 

 

 

** 예제 1117 (생성자) **

class Document{
	
	static int count = 0;
	String name;
	
	Document(){
		this("제목없음" + (++count));
	}
	
	Document(String name){
		this.name = name;
		System.out.println("문서 " + name + "이 생성되었습니다.");
	}
}

public class MySample1117 {

	public static void main(String[] args) {
		
		//생성자
		Document d1 = new Document();
		Document d2 = new Document("자바.txt");
		Document d3 = new Document();
		Document d4 = new Document();

	}

}

 

* 결과

문서 제목없음1이 생성되었습니다.
문서 자바.txt이 생성되었습니다.
문서 제목없음2이 생성되었습니다.
문서 제목없음3이 생성되었습니다.




** 상속(inheritance) **

- 기존의 클래스를 재사용하여 새로운 클래스를 작성하는 것

- 상속을 통해 부모의 클래스가 가지고 있는 모든 것을 (생성자 제외) 자식클래스가 물려받아 같이 공유하고 확장하는 기념

// new 객체가 만들어진 순간에는 호출되지만, 생성자를 물려받아 공유할 수는 없다.

- 예) class Child extends Parent {

        

        }

// extends 다음에 부모클래스는 한개만 쓸수 있다.

조상클래스 : 부모(Parent)클래스, 상위(super)클래스, 기반(base)클래스

자손클래스 : 자식(chlid)클래스, 하위(sub)클래스, 파생된(derived)클래스

 

- 예) class Parent(

                  int age;

         }

       

        class Child extends Parent {

        

        }


** 예제 1117_2 (상속) **

class Tv2{
	boolean power;		//전원상태(on/off)
	int channel;
	
	Tv2(){
		channel = 11;
		System.out.println("Tv2() 생성자...");
	}
	
	void power() {
		power = !power;
	}
	
	void channelUp() {		//부모변수가 증가함.
		++channel;
	}
	
	void channelDown() {
		--channel;
	}
}


class CaptionTv extends Tv2{
	
	boolean caption;		//자막상태
	int channel;
	
	CaptionTv(){			//생성자에서 부모가 호출된다.
//		super();			//생략되어있음. 무조건 첫번째줄에 와야함. super를 부르기때문에 부모 먼저 호출됨
		channel = 20;
		System.out.println("CaptionTv() 생성자...");
	}
	
	void displayCaption(String text) {
		int channel = 30;
		
		if(caption) {		//this.caption 에 this가 생략됨(지역변수 cation이 없기 때문)
			System.out.println("자막내용 : " + text);
		}
		
		System.out.println("부모 channel : " + super.channel);	//상속관계에서 부모인스턴스 지칭하는것 : super
		System.out.println("인스턴스 : " + this.channel);			//내 클래스의 인스턴스 지칭 : this
		System.out.println("channel : " + channel);
		//지역변수 인스턴스변수 부모변수 불러보기
	}
	
	int getChannel() {				//
		return super.channel;		//인스턴스변수(지역변수가 있을 시) : this.channel | 부모변수 : super.channel
	}
	
	
}

//변수값 찾을 때 지역변수 ->  자식인스턴스변수 -> 부모변수 순서로 찾는다. (cf : 메인메소드에서 channel찍으면 인스턴스 자식도있고 부모도있으)

public class MySample1117_2 {

	public static void main(String[] args) {
		
		//상속
		CaptionTv ctv = new CaptionTv();	//자식클래스 인스턴스ctv에 CaptionTv 객체 생성
		System.out.println("channel : " + ctv.channel);
		ctv.channel = 10;		//인스턴스변수에 10 대입.
		ctv.channelUp();
		System.out.println("channel : " + ctv.channel);
		ctv.displayCaption("Hello JAVA...");		//caption 디폴트값이 false라 출력 안됨.
		ctv.caption = true;
		ctv.displayCaption("Hello JAVA");
		ctv.power();								//없으면 아래 ctv.power가 false로 출력됨
		System.out.println("ctv.power : " + ctv.power);
		System.out.println("ctv.getChannel : " + ctv.getChannel());
		
	}

}

 

* 출력

Tv2() 생성자...
CaptionTv() 생성자...
channel : 20
channel : 10
부모 channel : 12
인스턴스 : 10
channel : 30
자막내용 : Hello JAVA
부모 channel : 12
인스턴스 : 10
channel : 30
ctv.power : false
ctv.getChannel : 12

 

// staic int channel이 아니지만 12 가 출력되는 이유 

 - ctv.channelUp();을 실행한후 값 유지 (이유 - ctv라는 동일한 인스턴스 객체이기때문 )


** 예제 1117_3 (상속) **

class Person{
	void breath() {
		System.out.println("숨쉬기");
	}
	
	void eat() {
		System.out.println("밥먹기");
	}
	
	void say() {
		System.out.println("말하기");
	}
}

class Student extends Person{
	void learn() {
		System.out.println("공부하기...");
	}
}

class Teacher extends Person{
	void teach() {
		System.out.println("설명하기...");
	}
}


public class MySample1117_3 {

	public static void main(String[] args) {
		
		//상속_2번 받는 경우
		
		Student s1 = new Student();
		s1.breath();
		s1.learn();
		
		Teacher t1 = new Teacher();
		t1.eat();
		t1.breath();
		t1.teach();
		
	}

}

** 예제 1117_4 (상속) **

class Point{		//x, y좌표값만
	int x;
	int y;
	
	Point(){
		this(0, 0);
	}
	
	Point(int x, int y){
		this.x = x;
		this.y = y;
	}
	
	String getXY() {
		return "(" + x + ", " + y + ")";	//문자열 형태로 보내주기 위해 만듬
	}
	
}

class Shape{		//색가지고 그리기만
	String color = "black";
	
	void draw() {
		System.out.printf("[color = %s] \n", color);
	}
}

class Circle extends Shape{
	Point center;		//??
	int r;
	
	Circle(){
		//Point p = new Point(0, 0);
		//this(p, 100);			//this() 는 항상 첫번째 라인에서 호출되어야 함.
		this(new Point(0, 0), 100);	//new Point(0, 0) -> new 객체생성한 주소값 반환
	}
	
	Circle(Point center, int r){
		this.center = center;
		this.r = r;
	}
	
	void draw() {
		System.out.printf("[center=(%d, %d), r=%d, color=%s]\n", center.x, center.y, r, color);
	}
}

class Triangle extends Shape{
	Point[] p = new Point[3];	// 좌표를 배열로 3개 생성함
	
//	Triangle() {
//		
//	}	//메인에서 new Triangle 객체생성할 때 오류안나기 위해 만들어준다.
		// 컬파일러 jdk가 생성자 만들어줌 - > 모든 클래스는 생성자가 하나 존재한다.
		// jdk는 생성자가 하나라도 존재하면 빈생성자 만들어주기 않기때문에 -> 빈생성자 하나 만들어 줘야한다.
	
	Triangle(Point[] p) {		//Point[] 클래스 배열타입을 받겠다는 의미.
		System.out.println("before : " + this.p.length);
		this.p = p;
		System.out.println("after : " + this.p.length);
	}
	
	void draw() {
		System.out.printf("[p1=%s, p2=%s, p3=%s, color=%s] \n", p[0].getXY(), p[1].getXY(), p[2].getXY(), color);
	}
}

public class MySample1117_4 {

	public static void main(String[] args) {
		
		//상속_도형그리기
		
		Point[] p = {
						new Point(100, 100),	//시작 주소값 넘겨줌
						new Point(140, 50),
						new Point(200, 100)
					};
		
		Triangle t = new Triangle(p);
		Circle c = new Circle(new Point(150, 150), 50);
		
		//바로 위 선을 분리하여 적용시 (더 직관적이지만 p2메모리가 더 할당되야한다.)
		//Point p2 = new Point(150, 150);
		//Circle c = new Circle(p2, 50);
		
		t.draw();	//삼각형 그리기
		c.draw();	//원그리기	

	}

}

** 예제 1117_5 **

class Person2{
	String name;
	String job;
	int age;
	
	Person2(String name, String job, int age){
		this.name = name;
		this.job = job;
		this.age = age;
	}
}

class Student2 extends Person2{	//생성자 때문에 오류남
	
	int score;
	
	Student2(String name, String job, int score, int age){
		
//		super.name = name;
//		super.job = job;
//		super.age = age;
		super(name, job, age);
		
		this.score = score;	
	}
	
	void print() {
//		System.out.println("이름 : " + super.name + ", 직업 : " +  super.job + ", 나이" + super.age + ", 점수" + this.score);
		System.out.println("이름 : " + name + ", 직업 : " +  job + ", 나이 : " + age + ", 점수 : " + score);
	}
}

class Teacher2 extends Person2{
	int pay;
	
	Teacher2(String name, String job, int age, int pay){
//		super.name = name;
//		super.job = job;
//		super.age = age;
		super(name, job, age);	//자식클래스에서 부모클래스의 변수에 값을 넣을때는 부모클래스의 생성자 이용하는 것이 좋다.
		this.pay = pay;
	}
	
	void print() {
//		System.out.println("이름 : " + super.name + ", 직업" + super.job + ", 나이" + super.age + ", 급여" + this.pay);	//올바른 문법
		System.out.println("이름 : " + name + ", 직업 : " + job + ", 나이 : " + age + ", 급여 : " + pay);
	}
}



public class Sample1117_5 {

	public static void main(String[] args) {
		// 상속
		
		Student2 s1 = new Student2("홍길동", "학생회장", 100, 19);
		s1.print();
		
		Teacher2 t1 = new Teacher2("펭수", "본부장", 40, 1000);
		t1.print();

	}

}

 

// s1이 바라보는 Person2와 t1이 바라보는 Person2는 다르다.

// super() -> 부모 생성자

// super.~~ -> 부모 인스턴스


** 실습 1117_6 **

/* 1
 부모클래스틑 Animal 클래의 멤버변수는 이름, 이동수단, 울음소리, 다리수로 정의
 각 멤버변수를 제어하는 메서드도 포함(get, set메서드를 활용하여 변수값 활용)
 단, get으로 시작하는 메서드는 해당 클래스에 인스턴스변수 값을 보내주는 것이며,
  set으로 시작하는 메서드는 해당 클래스에 인스턴스 변수에 값으르 저장하는 것임
 Animal 클래스를 상속받은 자식 클래스를 만들어서 각각의 이름, 이동수단, 울음소리, 다리수를 출력하는 프로그램.
 클래스는 Dog(강아지), Eagle(독수리), Lion(사자), Cat(고양이)
 출력은 name(이름), move(이동수단), cry(울음소리), leg(다리수)
 출력예)강아지 이름은 해피이고, 이동방법은 껑충껑충, 울음소리는 멍멍, 다리수는 4입니다.
    독수리 이름은 이글이고, 이동방법은 펄럭펄럭, 울음소리는 구구, 다린수는 2입니다.
    사자 이름은 어흥이고, 이동방법은 휙휙휙, 울음소리는 어흥어흥, 다리수는 4 입니다.
    고양이 이름은 나비이고, 이동방범은 껑충껑충, 울음소리는 야옹야옹, 다리수는 4입니다.
 단, 출력은 메인메서드에서 실행
 */

class Animal{
	
	
	String name;
	String move;
	String cry;
	int leg;
	
	Animal(){
		
	}
	
	Animal(String name, String move, String cry, int leg){
		this.name = name;
		this.move = move;
		this.cry = cry;
		this.leg = leg;
		
	}
	
	void setName(String name){		//set과 get은 세트로 잘 다닌다. set에서 값을 세팅하고 get에서 return반환값을 보낸다.
		this.name = name;
	}
	String getName(){
		return this.name;
	}
	
	void setMove(String move){
		this.move = move;
	}
	String getMove(){
		return this.move;
	}
	
	void setCry(String cry) {
		this.cry = cry;
	}
	String getCry() {
		return cry;
	}
	
	void setLeg(int leg) {
		this.leg = leg;
	}
	int getLeg() {
		return leg;
	}
	
}

class Dog extends Animal{
	Dog(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Eagle extends Animal{
	Eagle(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Lion extends Animal{
	Lion(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Cat extends Animal{
	Cat(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}


public class MySample1117_6 {

	public static void main(String[] args) {
		//상속
		
		Animal a = new Animal();
		Dog d = new Dog("해피", "껑충껑충", "멍멍", 4);
		Eagle e = new Eagle("이글", "펄럭펄럭", "구구", 2);
		Lion l = new Lion("어흥", "휙휙휙", "어흥어흥", 4);
		Cat c = new Cat("나비", "껑충껑충", "야옹야옹", 4);
		
		System.out.println("강아지 이름은 " + d.getName() + "이고, 이동방법은 " + d.getMove() + ", 울음소리는 " + d.getCry() + ", 다리수는 " + d.getLeg() + "입니다.");
		System.out.println("독수리 이름은 " + e.getName() + "이고, 이동방법은 " + e.getMove() + ", 울음소리는 " + e.getCry() + ", 다리수는 " + e.getLeg() + "입니다.");
		System.out.println("사자 이름은 " + l.getName() + "이고, 이동방법은 " + l.getMove() + ", 울음소리는 " + l.getCry() + ", 다리수는 " + l.getLeg() + "입니다.");
		System.out.println("고양이 이름은 " + c.getName() + "이고, 이동방법은 " + c.getMove() + ", 울음소리는 " + c.getCry() + ", 다리수는 " + c.getLeg() + "입니다.");
		

	}

}

 


** 선생님 풀이 1117_6 (상속) **

// MySample1117_6의 문제를 선생님 방법

class Animal2{
	String name;	//이름
	String move;	//이동수단
	String cry;		//울음소리
	int leg;		//다리수
	
	Animal2(){
		this("","","",0);
	}
	
	Animal2(String name, String move, String cry, int leg){
//		this.name = name;	//이름
//		this.move = move;	//이동수단
//		this.cry = cry;		//울음소리
//		this.leg = leg;
		
		//위 주석과 동일한 의미
		setName(name);
		setMove(move);
		setCry(cry);
		setLeg(leg);
	}

	
	String getName() {
		return this.name;
	}
	
	void setName(String name) {
		this.name = name;
	}
	
	String getMove() {
		return this.move;
	}
	
	void setMove(String move) {
		this.move = move;
	}
	
	String getCry() {
		return this.cry;
	}
	
	void setCry(String cry) {
		this.cry = cry;
	}
	
	int getLeg() {
		return this.leg;
	}
	
	void setLeg(int leg) {
		this.leg = leg;
	}

	
	
}

//-Animal 과 Animal을 상속받는 클래스들에 아무것도 없을때 오류가 안나는 이유 - 생성자 하나도 없으면 jdk에서 빈 생성자를 각각 하나씩 만들어주기 때문에
class Dog2 extends Animal{		
	Dog2(){
		this("","","",0);		//현단계에서 super(); 호출 하지 않게 하는 방법중 하나.
	}
	
	Dog2(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Eagle2 extends Animal{
	Eagle2(){
		
	}
	Eagle2(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Lion2 extends Animal{
	Lion2(){
		
	}
	Lion2(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
	
}

class Cat2 extends Animal{
	Cat2(){
		
	}
	Cat2(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
	
}


public class MySample1117_7 {

	public static void main(String[] args) {
		
		//상속
		//강아지 이름은 해피이고, 이동방법은 껑충껑충, 울음소리는 멍멍, 다리수는 4입니다.
		
		Dog2 d = new Dog2("해피","껑충껑충","멍멍",4);
		System.out.println("강아지 이름은 " + d.getName() + "이고, 이동방법은 " + d.getMove() + ", 울음소리는 " + d.getCry() + ", 다리수는 " + d.getLeg() + "입니다.");
		
		Eagle2 e = new Eagle2("이글", "펄럭펄럭", "구구", 2);
		System.out.println("독수리 이름은 " + e.getName() + "이고, 이동방법은 " + e.getMove() + ", 울음소리는 " + e.getCry() + ", 다리수는 " + e.getLeg() + "입니다.");
		
		Lion2 l = new Lion2("어흥이", "휙휙", "어흥어흥", 4);
		System.out.println("사자 이름은 " + l.getName() + "이고, 이동방법은 " + l.getMove() + ", 울음소리는 " + l.getCry() + ", 다리수는 " + l.getLeg() + "입니다.");
		
		Cat2 c = new Cat2("나비", "껑충꺼충", "야옹야옹", 4);
		System.out.println("고양이 이름은 " + c.getName() + "이고, 이동방법은 " + c.getMove() + ", 울음소리는 " + c.getCry() + ", 다리수는 " + c.getLeg() + "입니다.");
		
	}

}

 

 

 

 

// Generate 실행 예
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

** 메소드 오버로딩1115 **

//메서드 오버로딩
/* 1
 출력예)1
    13 (5, 8)
    2
    12 (5, 7.1)
    3
    12 (7.1, 5)
    4
    12.3 (7.1, 5.2)
    5
    210 (배열)
 */

class MyMath2{
	
	int j;
	
	int add(int a, int b) {
		System.out.println(++j);	// ++j 전치연산증감자 (초기값이 0이기때문)
		return a + b;
	}
	
	int add(int a, double b) {
		j++;
		System.out.println(j);
		return (int)(a + b);		//둘다 int로 해도되고 b에만 int 형변환해도된다.
	}
	
	int add(double a, int b) {
		System.out.println(++j);
		return (int)a + b;
	}
	
	double add(double a, double b){
		System.out.println(++j);
		return a + b;
	}
	
	int add(int[] a) {	//main의 배열 a와 같은 배열아니다.(a(임의로 사용_다른것도 가능)라는 배열을 매개 변수로 받겠다는 의미)
		System.out.println(++j);
		int i, sum = 0;
		for(i = 0 ; i < a.length ; i++) {
			sum += a[i];
		}
		return sum;
	}
}

public class MySample1116 {

	public static void main(String[] args) {
		
		//메서드 오버로딩
		/*
		 출력예)1
		 	  13		(5, 8)
		 	  2
		 	  12		(5, 7.1)
		 	  3
		 	  12		(7.1, 5)
		 	  4
		 	  12.3		(7.1, 5.2)
		 	  5
		 	  210		(배열)
		 */
		
		int[] a = new int[] {10,20,30,40,50,60};
		MyMath2 m = new MyMath2();
		MyMath2 m2= new MyMath2();
		
		System.out.println(m.add(5,8));
		System.out.println(m.add(5,7.1));
		System.out.println(m.add(7.1,5));
		System.out.println(m.add(7.1,5.2));
		System.out.println(m.add(a));
		
		System.out.println("\n");
		
		System.out.println(m2.add(5,3));
		System.out.println(m2.add(5,7.1));
		System.out.println(m2.add(7.1,5));
		System.out.println(m2.add(7.1,5.2));
		System.out.println(m2.add(a));

** 메소드 오버로딩1115_2 **

//메서드 오버로딩
/*
 실행결과)컴퓨터 가격은 : 10000원 입니다.
  제품은 : 컴퓨터 입니다.
  구매한 제품은 : 컴퓨터 이며, 10000원 입니다.
 */

class Computer{
	
	void show(int a){
		System.out.printf("컴퓨터 가격은 : %d원 입니다. \n", a);
	}
	
	void show(String a) {
		System.out.printf("제품은 : %s 입니다. \n", a);
	}
	
	void show(String a, int b) {
		System.out.printf("구매한 제품은 : %s 이며, %d원 입니다.", a, b);
	}
}

public class MySample1116_2 {

	public static void main(String[] args) {
		
		//메서드 오버로딩
		/*
		 실행결과)컴퓨터 가격은 : 10000원 입니다.
		 		제품은 : 컴퓨터 입니다.
		 		구매한 제품은 : 컴퓨터 이며, 10000원 입니다.
		 */
		
		Computer c = new Computer();
		c.show(10000);
		c.show("컴퓨터");
		c.show("컴퓨터", 10000);

	}

}

* 클래스 변수와 메서드, 인스턴스 변수와 메서드

//클래스 변수와 메서드, 인스턴스 변수와 메서드

class Member{
	
	int iv = 10;				//인스턴스 변수
	static int cv = 20;			//클래스 변수
	
	int iv2 = iv;				//가능(인스턴스 변수이기 때문에 가능)
//	static int cv2 = iv;		//불가능(iv는 인스턴스 변수이기 때문에)
//	
//	Member k = new Member();
//	static int cv2 = k.iv;		//불가능 (객체생성은 클래스영역말고 메서드에서 해야한다.) (Member객체 생성시기와 static변수 생성시기가 다르기 때문)
//	
	static int cv2 = new Member().iv;	//가능은 하나 사용하지 않은것을 권장
	
	static void staticMethod1() {		//클래스 메서드
		System.out.println(cv);
		System.out.println(iv);			//클래스 메소드에서 인스턴스 변수는 사용 불가능
		
		Member k = new Member();		//클래스 메소드에서 인스턴스 변수사용하려면 이렇게 해야한다.
		System.out.println(k.iv);
	}
	
	void instanceMethod1() {			//인스턴스 메서드
		System.out.println(cv);
		System.out.println(iv);
	}
	
	static void staticMethod2() {
		staticMethod1();
		instanceMethod1();				//클래스 메서드에서 인스턴스 메소드 호출하려면 아래와같이 객체생성 후 가능
		Member c = new Member();
		c.instanceMethod1();
	}
	
	
	void instanceMethod2() {
		staticMethod1();
		instanceMethod1();
	}



 

** 생성자 (Constructor) **

 

- 인스턴스가 생성될 때(new) 호출되는 인스턴스 초기화 메서드

  인스턴스 변수의 초기화 작업에 주로 사용

  메서드처럼 클래스 내에 선언되며, 리턴값이 없음(void 사용 안함)

 

- 생성자의 이름은 클래스의 이름과 같아야 함

- 생성자는 리턴 값이 없음

- 생성자에 메소드 오버로딩도 적용 가능하다.

 

예)

class Card{
	Card(){						//매개변수 없는 생성자
    ...
    }
    Card(String k, int num){	//매개변수 있는 생성자
    ...
    }

** 예제 ** 

class Car{
	String color;
	String gearType;
	int door;
	
	Car(){
		
	}
	
	Car(String c, String g, int d){
		color = c;
		gearType = g;
		door = d;
	}
}

public class MySample1116_3 {

	public static void main(String[] args) {
    
		Car c1 = new Car();
		c1.color = "white";
		c1.gearType = "auto";
		c1.door = 4;
		
		Car c2 = new Car("blue", "auto", 2);	//c2.color...에 대입안하고 생성자에 대입함
		
		System.out.println("c1의 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
		System.out.println("c1의 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);

	}

}

** 예제 **

public class MySample1116_3 {

	public static void main(String[] args) {
		
		//생성자
		
		Data2 d = new Data2();
		Data2 d2 = new Data2(10);
		
		System.out.println("d.value : " + d.value);
		System.out.println("d2.value : " + d2.value);
	}

}

class Data2{
	int value;
	
	Data2(){
		System.out.println("생성자 Data2() 호풀");
	}
	
	Data2(int x){
		System.out.println("생성자 Data2(int x) 호풀");
		value = x;
	}
}

** 실습 1116_3 **

* 두번째

class Car{
	
	String color;
	String gearType;
	int door;
    
    	//두번째
	
	Car(String a){
		color = a;
		gearType = "Auto";
		door = 4;
	}
//    // 위의 Car(String a)생성자의 매개변수명은 보통 a를 알아보기 쉽게 color로 할 경우
//	Car(String color){
//		this.color = color;		//this.color로하면 그 클래스에 있는 인스턴스변수를 받는다. (변수명이 같을경우 사용하는 this)
//								// = 뒤의 color는 매개변수 color를 받는다.
	}
	
	Car(){
		color = "white";
		gearType = "Auto";
		door = 4;
	}
	
}

public class MySample1116_3 {

	public static void main(String[] args) {
		
		//두번째
		//매개변수 1개는 color에 적용. 매개변수 없을 때는 white로 지정
		//gearType = auto, door = 4로 지정
		System.out.println("main 시작 c1생성");
		Car c1 = new Car();
		System.out.println("main 시작 c2생성");
		Car c2 = new Car("blue");

		System.out.println("c1의 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
		System.out.println("c1의 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);
		
	}

}

** 예제 (this.) **

class Car{
	
	String color;
	String gearType;
	int door;
    
    Car(){
//		this.color = "white";
//		this.gearType = "auto";
//		this.door = 4;
		this("white", "auto", 4);		//this 같은 클래스 내에서 다른생성자 호출(매개변수 3개를 호출한다는 의미)
		System.out.println("매개변수 없음.");
	}
	
	Car(String color){
//		this.color = color;
//		this.gearType = "auto";
//		this.door = 4;
		this(color, "auto", 4);
		System.out.println("매개변수 1개 color");
	}
	
	Car(String color, String gearType){			//생성자에서 생성자 호출 가능
//		this.color = color;
//		this.gearType = gearType;
//		this.door = 2;
		this(color, gearType, 2);
		System.out.println("매개변수 2개 color, gearType");
	}
	
	Car(String color, String gearType, int door){
		this.color = color;
		this.gearType = gearType;
		this.door = door;
		System.out.println("매개변수 3개");
	}
    
    
    public class MySample1116_3 {

	public static void main(String[] args) {
    
    	System.out.println("main 시작 c1생성");
		Car c1 = new Car();		// 객체생성하면서 매개변수없는 생성자 호출
		System.out.println("main 시작 c2생성");
		Car c2 = new Car("blue");
		System.out.println("main 시작 c3생성");
		Car c3 = new Car("red", "auto");

		System.out.println("c1의 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
		System.out.println("c2의 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);		
		System.out.println("c3의 color = " + c3.color + ", gearType = " + c3.gearType + ", door = " + c3.door);
		
	}

}

 

결과

main 시작 c2생성
매개변수 3개
매개변수 1개 color
main 시작 c3생성
매개변수 3개
매개변수 2개 color, gearType
c1의 color = white, gearType = auto, door = 4
c2의 color = blue, gearType = auto, door = 4
c3의 color = red, gearType = auto, door = 2


** 예제 1116_4 **

* 생성자를 이용한 인스턴스 복사

class Car1{
	String color;
	String gearType;
	int door;
	
	
	Car1(){
		this("white", "auto", 6);	//생성자에서 다른생성자 호출시(this) 항상 첫번째줄에 와야한다.
		this.color = "white";
		this.gearType = "auto";
		this.door = 6;
	}
	
	Car1(Car1 c){					//매개변수가 객체(참조형 변수)
		this(c.color, c.gearType, c.door);
//		this.color = c.color;
//		this.gearType = c.gearType;
//		this.door = c.door;
	}
	
	Car1(String color, String gearType, int door){
		this.color = color;
		this.gearType = gearType;
		this.door = door;
	}
	
	
}

public class MySample1116_4 {

	public static void main(String[] args) {
		
		//생성자 - 생성자를 이용한 인스턴스 복사
		Car1 c1 = new Car1();
		Car1 c2 = new Car1(c1);
		Car1 c3 = new Car1(c1);
		
		System.out.println("c1 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
		System.out.println("c2 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);
		System.out.println("c3 color = " + c3.color + ", gearType = " + c3.gearType + ", door = " + c3.door);
		
		
		
		c1.door = 50;
		c2.color = "pink";
		
		System.out.println("c1 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door); 
		System.out.println("c2 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);
		System.out.println("c3 color = " + c3.color + ", gearType = " + c3.gearType + ", door = " + c3.door);
		

	}

}

** 예제 1116_5 **

* 클래스 초기화 블럭 / 인스턴스 초기화 블럭

public class MySample1116_5 {
	
//	static int cv = 1;
//	int iv = 2;
//	
//	//클래스 초기화 블럭 (생성자보다 먼저 실행됨) -> 한번만실행 
//	static {
//		System.out.println("static 초기화영역");
//		cv = 10;
//	}
//	
//	//인스턴스 초기화 블럭 -> new 생길때 실행
//	{
//		System.out.println("인스턴스 초기화 영역");
//		iv = 20;
//	}
//	
//	MySample1116_5(){
//		System.out.println("MySample1116_5() 생성자호출");
//	}
	

//	public static void main(String[] args) {
//		
//		//초기화 블럭
//		System.out.println("main 메서드 시작");
//		MySample1116_5 m1 = new MySample1116_5();
//		
//		System.out.println("main메서드 두번째 실행");
//		MySample1116_5 m2 = new MySample1116_5();
//		
//		System.out.println("main 메서드 끝");
//		
//	}
	
	public static void main(String[] args) {
		
		Product p1 = new Product();
		Product p2 = new Product();
		Product p3 = new Product();
		
		System.out.println("p1 제품번호 serialNo : " + p1.serialNo);
		System.out.println("p2 제품번호 serialNo : " + p2.serialNo);
		System.out.println("p3 제품번호 serialNo : " + p3.serialNo);
		System.out.println("객체 생성 수  : " + Product.count);
		
	}

}

class Product{
	static int count = 0;
	int serialNo;
	
	{
		System.out.println("인스턴스 초기화 블럭 시작 count : " + count + ", sreialNo : " + serialNo);
		
		++count;
		serialNo = count;
		
		System.out.println("인스턴스 초기화 블럭 끝 count : " + count + ", sreialNo : " + serialNo);
		
	}
	
	Product(){
		System.out.println("Product() 생성자");
	}
	
	
	
}

** 예제 1116_6 **


public class MySample1116_6 {

	public static void main(String[] args) {
		
		//초기화 블럭
		/*
		 출력예)Static method : 1
		 	  Static block : 2
		 	  Static method : 3
		 	  instance method : 4
		 	  instance block : 5
		 	  instance method : 6
		 	  constructor : 7
		 	  instance method : 8
		 	  instance block : 9
		 	  instance method : 10
		 	  constructor : 11
		 */
		
		STest.test();
		STest a = new STest();
		STest b = new STest();

	}

}

class STest{		//클래스 영역에 정의된 변수는 초기화(입주청소) 해준다.
	
	static int cnt;
	
	static {		//클래스 초기화 영역
		test();		//test();만 보고 클래스 메서드인것과 같은 클래스내에 정의되어있다를 알 수 있음.
		cnt++;
		System.out.println("static block : " + cnt);
	}
	
	{				//인스턴스 초기화 영역
		instanceMethod();
		cnt++;
		System.out.println("instance block : " + cnt);
	}
	
	STest(){
		instanceMethod();
		cnt++;
		System.out.println("constructor : " + cnt);
	}
	
	static void test() {
		cnt++;		//클래스 변수임을 알 수 있다.
		System.out.println("static method : " + cnt);
	}
	
	void instanceMethod() {
		cnt++;
		System.out.println("instance method : " + cnt);
	}
	
}


// 생성자 객체 생성 (입주청소) -> 인스턴스 초기화 블럭 실행 -> 생성자 실행

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

* 기본형 매개변수

class Data
{
	int x;
	int y;
}


public class MySample {

	//객체지향프로그램 = 기본형 매개변수 시작
	public static void main(String[] args) {
		
		Data d = new Data();
		d.x = 10;
		
		System.out.println("main() x : " + d.x);
		
		change(d.x);	
		//클래스or인스턴스명이 앞에 안와도 괜찮은 이유 : 같은 클래스 내에 있는 클래스메소드(static) 호출이기때문
		
		System.out.println("main() after x : " + d.x);

	}
	
	//기본형 매개변수
	static void change(int x)	//void : change 끝났을 때 반환되는 값이 없다.
	{
		x = 1000;
		System.out.println("change() x : " + x);
	}

* 참조형 매개변수

class Data
{
	int x;
	int y;
}


public class MySample {
	
    //참조형 매개변수 시작
	public static void main(String[] args) 
	{
		Data d = new Data();
		d.x = 10;
		
		System.out.println("main() x : " + d.x);
		
		change(d);
		System.out.println("main() after x : " + d.x);
	} 
	
	static void change(Data d)
	{
		d.x = 1000;
		System.out.println("change() x : " + d.x);
	}
    
}

* 참조형 반환타임(return) + 참조형 매개변수

 

class Data
{
	int x;
	int y;
}


public class MySample {
	
    //참조형 반환타입(리턴타입) 시작
	public static void main(String[] args) 
	{
		Data d = new Data();
		d.x = 10;
		
		Data d2 = change(d);
		
		System.out.println("d.x = " + d.x);
		System.out.println("d2.x = " + d2.x);		//d.x와 d2.x의 값은 동일하지만 서로다른 주소값이다.
	}
	
	static Data change(Data d)
	{
		Data tmp = new Data();
		tmp.x = d.x  ;
		
		return tmp;
	}

}

* 참조형 반환타입 / 기본형 매개변수

class Data
{
	int x;
	int y;
}


public class MySample {

	//매개변수는 기본현, 반환타입(return타입) 참조형 시작
	public static void main(String[] args) 
	{
		int a = 5;
		Data d;
		
		System.out.println("main() a : " + a);
		
		d = change(a);
		
		System.out.println("main() after d.x : " + d.x);
		
	}
	
	static Data change(int a)
	{
		Data tmp = new Data();
		tmp.x = a + 10;
		
		return tmp;
	}
	//매개변수는 기본현, 반환타입(return타입) 참조형 끝
    
}

** 실습_참조형 매개변수/참조형 반환타입 **

/* 1
 문제)Data객체에 y변수 추가하고 main에서 2개 정수를 입력받아 Data 객체 각 변수에 대입하고.
   main에서 각 값을 출력한 후 copy 메서드를 통해 값에 2를 곱한 결과를 출력하는 프로그램.
 입력예)정수 2개를 입력하세요.>10 20
 출력예)main 입력값 d.x = 10, d.y : 20
    copy 메서드 d.x = 10, d.y : 20
    copy 메서드 tmp.x = 20, tmp.y : 40
    main 마지막 d.x = 10, d.y : 20
    main 마지막 d2.x = 20, d2.y : 40
 */

import java.util.Scanner;

class Data
{
	int x;
	int y;
}


public class MySample {
	public static void main(String[] args) 
	{
		Scanner scn = new Scanner(System.in);
		System.out.print("정수 2개를 입력하세요.>");
		
		Data d = new Data();
		d.x = scn.nextInt();
		d.y = scn.nextInt();
		
		System.out.println("main 입력값 d.x = " + d.x + ", d.y : " + d.y);
		
		copy(d);
		
		Data d2 = copy(d);
		
		System.out.println("main 마지막 d.x = " + d.x + ", d.y : " + d.y);
		System.out.println("main 마지막 d2.x = " + d2.x + ", d2.y : " + d2.y);
	}
	
	static Data copy(Data d)	//main d와 d자체는 다른 주소지만, 두개의 d가 바라보는 주소값은 같다.
	{
		System.out.println("copy 메서드 d.x = " + d.x + ", d.y : " + d.y);
		Data tmp = new Data();
		tmp.x = d.x * 2;
		tmp.y = d.y * 2;
		System.out.println("copy 메서드 tmp.x = " + tmp.x + ", tmp.y : " + tmp.y);
		
		return tmp;
	}

}

* 배열을 이용한 참조형 매개변수

public class MySample {
	
    //배열을 이용한 참조형 매개변수
	public static void main(String[] args) 
	{
		int[] a = {10, 20};
		
		System.out.println("main() a[0] : " + a[0]);
		
		change(a);
		
		System.out.println("main() a[0] : " + a[0]);
	}
	
	static void change(int[] x)
	{
		x[0] = 2000;
		System.out.println("change() x : " + x[0]);
	}
}

** 실습1115 **

/* 2
 문제)위와 동일한 형태로 하되 결과는 다르게 구현
 출력예)main 입력값 d.x = 10, d.y : 20
    copy 메서드 tmp.x = 10, tmp.y : 20
    copy 메서드 tmp.x = 20, tmp.y : 40
    main 마지막 d.x = 20, d.y : 40
 단, copy메서드의 반환타입(리턴타입) 없음.
 */

import java.util.Scanner;

class Data
{
	int x;
	int y;
}


public class MySample {
	
    public static void main(String[] args) 
	{
		Scanner scn = new Scanner(System.in);
		System.out.print("정수 2개를 입력하세요.>");
		
		Data d = new Data();
		d.x = scn.nextInt();
		d.y = scn.nextInt();
		
		System.out.println("main 입력값 d.x = " + d.x + ", d.y : " + d.y);
		
		copy(d);
		
		System.out.println("main 마지막 d.x = " + d.x + ", d.y : " + d.y);
	}
	
	static void copy(Data tmp)
	{
		System.out.println("copy 메서드 tmp.x =" + tmp.x + ", tmp.y : " + tmp.y);
		tmp.x = tmp.x * 2;
		tmp.y = tmp.y * 2;
		System.out.println("copy 메서드 tmp.x =" + tmp.x + ", tmp.y : " + tmp.y);	
	}
}

** 실습1115 **

/* 3
 문제)배열에 {3, 2, 1, 6, 5, 4}를 초기값으로 선언후에 오름차순으로 정렬하여 출력하는 프로그램.
   단, 각 메서드는 배열출력은 printArr, 배열의 모든 합은 sumArr,
    배열 정렬은 sortArr로 선언하여 구현함.
    sumArr 메서드만 리턴타입이 존재함.
 출력예)[3,2,1,6,5,4]
    [1,2,3,4,5,6]
    sum = 21
 */

//배열은 시작주소와 길이를 같이 가지고 다닌다.

 

import java.util.Scanner;

//class Data
//{
//	int x;
//	int y;
//}


public class MySample1115{

	/* 3
	 문제)배열에 {3, 2, 1, 6, 5, 4}를 초기값으로 선언후에 오름차순으로 정렬하여 출력하는 프로그램.
	 	 단, 각 메서드는 배열출력은 printArr, 배열의 모든 합은 sumArr,
	 	 	배열 정렬은 sortArr로 선언하여 구현함.
	 	 	sumArr 메서드만 리턴타입이 존재함.
	 출력예)[3,2,1,6,5,4]
	 	  [1,2,3,4,5,6]
	 	  sum = 21
	 */
	
	//배열은 시작주소와 길이를 같이 가지고 다닌다.
	
	public static void main(String[] args)
	{
		int[] arr = new int[] {3, 2, 1, 6, 5, 4};	//int[] arr = {3, 2, 1, 6, 5, 4}; 이렇게해도된다.
		printArr(arr);
		sortArr(arr);
		printArr(arr);
		System.out.println("sum = " + sumArr(arr));
	}
	
	static void sortArr(int[] x)	//클래스 메서드 | int[] x -> 배열로 받겠다는 의미
	{
		int i, j, tmp;
		
		for(i = 0 ; i < x.length - 1 ; i++)
		{
			for(j = i + 1 ; j < x.length ; j++)
			{
				if(x[i] > x[j])
				{
					tmp = x[i];
					x[i] = x[j];
					x[j] = tmp;
				}
			}
		}
	}
	
	static void printArr(int[] arr)
	{
		int i;
		System.out.print("[");
		for(i = 0 ; i < arr.length ; i++) 
		{
//			//쉼표를 먼저 찍을 경우
//			if(i != 0 && i != arr.length)
//				System.out.print(", ");
			
			System.out.printf("%d", arr[i]);
			if(i != arr.length -1)
				System.out.print(", ");

		}
		System.out.print("] \n");
	}
	
	static int sumArr(int[]a)
	{
		int sum = 0, i;
		for(i = 0 ; i < a.length ; i++)
		{
			sum += a[i];
		}
		return sum;
	}
	
}

 


** 실습1115_2 **

//객체지향프로그램 - 참조형 매개변수
/* 4
 문제)두 정수를 Add클래스 a, b변수에 입력받은 후 더하기, 뺴기, 곱하기, 나누기 메서드를 이용하여 
   결과를 모두 main에서 출력하는 프로그램.(결과는 c변수 사용)
   단, 더하기 add, 빼기 sub, 곱하기 mul, 나누기 div 로 정의하며, 
     참조형 매개변수를 활용한 메서드 구현, 전부 반환타입이 없음.
 입력예)두 정수를 입력하세요.>5 3
 출력예)더하기 : 8
     뺴기 : 2
     곱하기 : 15
     나누기 : 1
 */

import java.util.Scanner;

class Add
{
	int a;
	int b;
	int c;
}

public class MySample1115_2 {

	public static void main(String[] args) {
		
		//객체지향프로그램 - 참조형 매개변수
		/* 4
		 문제)두 정수를 Add클래스 a, b변수에 입력받은 후 더하기, 뺴기, 곱하기, 나누기 메서드를 이용하여 
		 	 결과를 모두 main에서 출력하는 프로그램.(결과는 c변수 사용)
		 	 단, 더하기 add, 빼기 sub, 곱하기 mul, 나누기 div 로 정의하며, 
		 	  	참조형 매개변수를 활용한 메서드 구현, 전부 반환타입이 없음.
		 입력예)두 정수를 입력하세요.>5 3
		 출력예)더하기 : 8
		 	   뺴기 : 2
		 	   곱하기 : 15
		 	   나누기 : 1
		 */
		
		Scanner scn = new Scanner(System.in);
		
		System.out.print("두 정수를 입력하세요.>");
		
		Add ad = new Add();		//Add 클래스의 인스턴스 객체 생성
		
		ad.a = scn.nextInt();
		ad.b = scn.nextInt();
		
		add(ad);
		System.out.println("더하기 : " + ad.c);
		sub(ad);
		System.out.println("빼기 : " + ad.c);
		mul(ad);
		System.out.println("곱하기 : " + ad.c);
		div(ad);
		System.out.println("나누기 : " + ad.c);
	}
	
	
	static void add(Add a){
		a.c = a.a + a.b;
	}
	
	static void sub(Add ad){
		if (ad.a > ad.b)
			ad.c = ad.a - ad.b;
		else
			ad.c = ad.b - ad.a;
	}
	
	static void mul(Add ad){
		ad.c = ad.a * ad.b;
	}
	
	static void div(Add ad){
		ad.c = ad.a / ad.b;
	}

}

** 실습1115_2 **

//참조형 매개변수를 이용한 메서드를 Add 클래스에 구현한 경우

 

//참조형 매개변수를 이용한 메서드를 Add 클래스에 구현한 경우
class Add{
	
	int a;
	int b;
	int c;
	
	static void add(Add a){
		a.c = a.a + a.b;
	}
	
	static void sub(Add ad){
		if (ad.a > ad.b)
			ad.c = ad.a - ad.b;
		else
			ad.c = ad.b - ad.a;
	}
	
	static void mul(Add ad){
		ad.c = ad.a * ad.b;
	}
	
	void div(Add ad){		//인스턴스 메소드
		ad.c = ad.a / ad.b;
	}
}

//참조형 매개변수를 이용한 메서드를 Add 클래스에 구현한 경우

public class MySample1115_2 {

	public static void main(String[] args) {
		
		
		Scanner scn = new Scanner(System.in);
		
		System.out.print("두 정수를 입력하세요.>");
		
		Add ad = new Add();		//Add 클래스의 인스턴스 객체 생성
		
		ad.a = scn.nextInt();
		ad.b = scn.nextInt();
		
		Add.add(ad);
		System.out.println("더하기 : " + ad.c);
		Add.sub(ad);
		System.out.println("빼기 : " + ad.c);
		Add.mul(ad);
		System.out.println("곱하기 : " + ad.c);
		ad.div(ad);
		System.out.println("나누기 : " + ad.c);
	}

}

 



** 메서드 오버로딩 (overloading) **

한 클래스 내에 같은 이름의 메서드를 여러개 정의

메서드 이름이 같아야 함

매개변수의 개수 또는 타입이 다르게 구현

반환 타입은 오버로딩을 구현하는데 아무런 영향을 주지 못함

 

예 : System.out.println 메서드

매개변수로 지정하는 값의 타팁에 따라 호출되는 println메서드가 다름

void println()

 


** 실습1115_3 **

public class MySample1115_3 {

	public static void main(String[] args) {
		
		//메서드 오버로딩
		MySample1115_3 m = new MySample1115_3();
		System.out.println("sum()메서드 매개변수 2개 : " + m.sum(5,  8));
		System.out.println("sum()메서드 매개변수 3개 : " + m.sum(1, 2, 3));
		m.sum(2);
		
	}
	
	int sum(int a, int b){
		return a + b;
	}
	
	void sum(int a) {
		System.out.println("sum()메서드 1개 a : " + a);
	}
	
	int sum(int a, int b, int c){
		return a + b + c;
	}

}

** 실습1115_4 **

// 메소드 오버로딩

class MyMath{
	
	int a;
	int b;
	
	int add(int a, int b) {
		return a + b;
	}
	
	int subtract(int a, int b) {
		return a - b;
	}
	
	int multiply(int a, int b) {
		return a * b;
	}
	
	int divide(int a, int b) {
		return a / b;
	}
	
	int add() {
		return a + b;
	}
	
	int subtract() {
		return a - b;
	}
	
	int multiply() {
		return a * b;
	}
	
	int divide() {
		return a / b;
	}
}


public class MySample1115_4 {

	public static void main(String[] args) {
		
		//메서드 오버로딩
		MyMath m = new MyMath();
		m.a = 200;
		m.b = 100;
		
		System.out.println(m.add(200, 100));
		System.out.println(m.subtract(200, 100));
		System.out.println(m.multiply(200, 100));
		System.out.println(m.divide(200, 100));
		
		System.out.println(m.add());
		System.out.println(m.subtract());
		System.out.println(m.multiply());
		System.out.println(m.divide());

	}
	
}

** 실습1115_5 **

//메서드 오버로딩
/*
 출력예)Java
    a : 100
    a : 89 b : 99
    double a : 99.12
    total rest 결과 : 198.24 (바로 위 99.12 * 2 한 값)
    단, 인스턴스변수 없음
 */


class OverLoad1{
	int a, b;
	
	void test() {
		System.out.println("Java");
	}
	
	void test(int a) {
		System.out.println("a : " + a);
	}
	
	void test(int a, int b) {
		System.out.println("a : " + a + "  b : " + b);
		
	}
	
	double test(double a) {
		System.out.println("double a : " + a);
		return a * 2;
		
	}
		
}

public class MySample1115_5 {

	public static void main(String[] args) {
		
		//메서드 오버로딩
		/*
		 출력예)Java
		 	  a : 100
		 	  a : 89	b : 99
		 	  double a : 99.12
		 	  total rest 결과 : 198.24 (바로 위 99.12 * 2 한 값)
		 	  단, 인스턴스변수 없음
		 */
		
		OverLoad1 o = new OverLoad1();
		double t;
		
		o.test();
		o.test(100);
		o.test(89, 90);
		t = o.test(99.12);		// t = 의 뜻은 o.test(99.12)에 리턴이있다는 의미.
		System.out.println("total rest 결과 : " + t);

	}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/17 수업 (15회차) _ 상속  (1) 2023.11.17
11/16 수업 (14회차) _ 메소드 오버로딩 / 생성자  (0) 2023.11.16
11/14 수업 (12일차)  (1) 2023.11.14
11/13 수업 (11일차)  (2) 2023.11.13
11/10 수업 (10일차)  (0) 2023.11.10

** 실습 1113 **

class Card
{
	String kind;	//인스턴스 변수
	int number;
	
	static int width = 100;		//클래스변수 -> 객체생성안해도 된다. Card. 으로 호출함
	static int height = 250;	//클래스변수
}

public class MySample1114 {

	public static void main(String[] args) {
		
		//클래스
		System.out.println("Card.width = " + Card.width);	//문법이 맞게 호출함
		System.out.println("Card.height = " + Card.height);
		
		Card c1 = new Card();	//ㅇ
		c1.kind = "Heart";
		c1.number = 7;
		
		Card c2 = new Card();
		c2.kind = "Spade";
		c2.number = 4;
		
		System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")");
		System.out.println("c2은 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")");
		c1.number = 12;
		c2.number = 8;
		
		c1.width = 50;
		c2.width = 80;
		
		System.out.println("변경 후============================");
		
		System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")");
		System.out.println("c2은 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")");
		
	}

}

** 실습 1114_2 **

import java.util.Scanner;

class Math2
{
	//인스턴스 메서드
	int add(int a, int b)
	{
		System.out.println("add메서드 시작 : a = " + a + ", b = " + b);
		a = a + 10;
		b = b + 10;
		
		int result = a + b;
		
		System.out.println("add메서드 끝 : a = " + a + ", b = " + b);
		return result;
	}
}

public class MySample1114_2 {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		
		//계산기 클래스
		System.out.print("정수 2개를 입력하세요.>");
		int a = scn.nextInt();
		int b = scn.nextInt();
		
		System.out.println("main 메서드 호출 전 : a = " + a + ", b = " + b);
		
		Math2 m = new Math2();
		int c = m.add(a, b);
		
		System.out.println("main 메서드 호출 후 : a = " + a + ",b = " + b + ", c = " + c);
        
	}
}

** 실습 1114_2 **

/* 1
 문제)두 정수를 입력받아 더하기, 빼기, 곱하기, 나누기 연산결과 출력.
 입력예)두 정수를 입력하세요.>5 3
 출력예)add(a, b) = 8
    subtract(a, b) = 2
    multiply(a, b) = 15
    divide(a, b) = 1.66666666666667(소수점은 실수로 표련 - double)
 단, 클래스는 Math3로 한다.
 */

import java.util.Scanner;

class Math3
{
	int add(int a, int b)
	{
		return a + b;
	}
	
	int subtract(int a, int b)
	{
		//항상 큰수에서 작은수를 뺄수있게 처리
		if(a > b)
			return a - b;
		else		//return을 하려면 모든경우가 들어가야한다 -> esle 안쓰면 오류난다.
			return b - a;	
	}
	
	int multiply(int a, int b)
	{
		return a * b;
	}
	
	double divide(int a, int b)
	{
		return (double)a / b;
	}
}

public class MySample1114_2 {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
        
        System.out.print("두 정수를 입력하세요.>");
		int a = scn.nextInt();
		int b = scn.nextInt();
		
		Math3 m3 = new Math3();
		
		int i = m3.add(a, b);
		int j = m3.subtract(a, b);
		int k = m3.multiply(a, b);
		double l = m3.divide(a, b);
		
		System.out.println("add(a, b) = " + i);
		System.out.println("subtract(a, b) = " + j);
		System.out.println("multiply(a, b) = " + k);
		System.out.println("divide(a, b) = " + l);
		
		//변수 선언 안하고 바로 프린트
		System.out.println("add(a, b) = " + m3.add(a, b));
		System.out.println("subtract(a, b) = " + m3.subtract(a, b));
		System.out.println("multiply(a, b) = " + m3.multiply(a, b));
		System.out.println("divide(a, b) = " + m3.divide(a, b));   
	}
}

** 실습 1114_2 **

//위 문제를 인스턴스변수를 이용하여 더하기, 빼기, 곱하기, 나누기 연산결과 출력.

import java.util.Scanner;

class Math3
{
	int a, b;
	
	int add()
	{
		return a + b;
	}
	
	int subtract()
	{
		//항상 큰수에서 작은수를 뺄수있게 처리
		if(a > b)
			return a - b;
		else		//return을 하려면 모든경우가 들어가야한다 -> esle 안쓰면 오류난다.
			return b - a;	
	}
	
	int multiply()
	{
		return a * b;
	}
	
	double divide()
	{
		return (double)a / b;
	}
}

public class MySample1114_2 {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
        
        	Math3 m3 = new Math3();
		
		System.out.print("두 정수를 입력하세요.>");
		
		int a = scn.nextInt();
		int b = scn.nextInt();
		m3.a = a;
		m3.b = b;
		
		// int a = scn.nextInt(); / m3.a = a; 합쳐서 사용
		m3.a = scn.nextInt();
		m3.b = scn.nextInt();
        
        	System.out.println("add(a, b) = " + m3.add());
		System.out.println("subtract(a, b) = " + m3.subtract());
		System.out.println("multiply(a, b) = " + m3.multiply());
		System.out.println("divide(a, b) = " + m3.divide());
	}
}

** 실습 1114_2 **

//위와 동일한 결과로 클래스 변수를 이용한 계산기
//Math3 클래스에대한 객체인스턴스 m1, m2에 대해서 정의한 후
//m1과 m2에서 각각 같은 변수를 공유한다는 의미로 출력
//클래스 변수병은 기존 소스를 수정하여 a, b 그대로 사용

import java.util.Scanner;

class Math3
{
	static int a, b;
	
	int add()
	{
		return a + b;
	}
	
	int subtract()
	{
		//항상 큰수에서 작은수를 뺄수있게 처리
		if(a > b)
			return a - b;
		else		//return을 하려면 모든경우가 들어가야한다 -> esle 안쓰면 오류난다.
			return b - a;	
	}
	
	int multiply()
	{
		return a * b;
	}
	
	double divide()
	{
		return (double)a / b;
	}
}

public class MySample1114_2 {

	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		
		System.out.print("두 정수를 입력하세요.>");
		
		Math3.a = scn.nextInt();
		Math3.b = scn.nextInt();
		
		Math3 m1 = new Math3();
		Math3 m2 = new Math3();
		
		System.out.println("add(a, b) = " + m1.add());
		System.out.println("subtract(a, b) = " + m1.subtract());
		System.out.println("multiply(a, b) = " + m1.multiply());
		System.out.println("divide(a, b) = " + m1.divide());
		
		System.out.println("add(a, b) = " + m2.add());
		System.out.println("subtract(a, b) = " + m2.subtract());
		System.out.println("multiply(a, b) = " + m2.multiply());
		System.out.println("divide(a, b) = " + m2.divide());   
	}
}



 

** 스택  & 큐 **

 

* 스택

데이터를 일시적으로 저장하기위해 사용하는 자료구조로, 데이터이 입력과 출력순서는 후입선루 (LIFO.Last In First Out)

가장 나중에 넣은 데이터를 가장 먼저 꺼내는 구조.

 


** 실습 1114_3 **

public class MySample1114_3 {

	static void firstMethod()
	{
		System.out.println("firstMethod() start...");		//2
		secondMathod();
		System.out.println("firstMethod() end...");			//7
	}
	
	static void secondMathod()
	{
		System.out.println("secondMethod() start...");		//3
		thiredMathod();
		System.out.println("secondMethod() end...");		//6
	}
	
	static void thiredMathod()
	{
		System.out.println("thiredMathod start...");		//4
		System.out.println("thiredMathod end...");			//5
	}
	
	public static void main(String[] args) {
		
		//메서드 호출 순서 - 스택
		System.out.println("main start...");				//1
		firstMethod();
		System.out.println("main end...");					//8

	}

}

** 실습1114_3 **

/* 1
 문제)정수 2개를 입력받아 메서드 호출전과 후에 대한 결과를 출력하는 프로그램 작성
 입력예)정수 2개를 입력하세요.>5 10
 출력예)호출 전 a : 5, b : 10 (main메서드에서 출력)
    add 메서드 a : 10, b : 20 (add메서드에서 출력)
    결과 : 30 (main메서드에서 출력)
    호출 후 a : 5, b : 10 (main메서드에서 출력)
 */

import java.util.Scanner;

class Math4
{
	int add(int a, int b)
	{
		a = a * 2;
		b = b * 2;
		int result = a + b;
		System.out.println("add 메서드 a : " + a + ", b : " + b);
		return result;
	}
}

public class MySample1114_3 {
	public static void main(String[] args) {
		
		Scanner scn = new Scanner(System.in);
        
        	System.out.print("정수 2개를 입력하세요.>");
		int a = scn.nextInt();
		int b = scn.nextInt();
		
		System.out.println("호출 전 a : " + a + ", b : " + b);
		
		Math4 x  = new Math4();
		
//		x.add(a, b);
		System.out.println("결과 : " + x.add(a, b));
		System.out.println("호출 후 a : " + a + ", b : " + b);
		
	}

}

//위와 동일한 결과로 지역변수가 아닌 인스턴스 변수로 이용시.

import java.util.Scanner;

class Math4
{
	//인스턴스 변수 적용시
	int a, b;
	
	int add(int a, int b)
	{
		a = a * 2;
		b = b * 2;
		int result = a + b;
		System.out.println("add 메서드 a : " + a + ", b : " + b);
		return result;
	}
}
public class MySample1114_3 {
	public static void main(String[] args) {
		
		Scanner scn = new Scanner(System.in);
        
        		//위와 동일한 결과로 지역변수가 아닌 인스턴스 변수로 이용시.
		
		Math4 m = new Math4();		//인스턴스 변수쓰려고 객체생성 
		
		System.out.print("정수 2개를 입력하세요.>");
		m.a = scn.nextInt();
		m.b = scn.nextInt();
		
		System.out.println("호출 전 a : " +m. a + ", b : " + m.b);
		System.out.println("결과 : " + m.add(m.a, m.b));
		System.out.println("호출 후 a : " + m.a + ", b : " + m.b);

	}

}

//위와 동일할 결과로 지역변수나 인스턴스 변수가 아닌 클래스변수로 이용시.

import java.util.Scanner;

class Math4
{
	//클래스 변수만 이용하여 출력.
	
    static int a, b;
		
		int add()
		{
			a = a * 2;
			b = b * 2;
			int result = a + b;
			System.out.println("add 메서드 a : " + a + ", b : " + b);
			return result;
		}
}

public class MySample1114_3 {
	public static void main(String[] args) {
		
		Scanner scn = new Scanner(System.in);
        
        	System.out.print("정수 2개를 입력하세요.>");
		Math4.a = scn.nextInt();
		Math4.b = scn.nextInt();
		
		Math4 m = new Math4();
		
		System.out.println("호출 전 a : " + Math4. a + ", b : " + Math4.b);
		System.out.println("결과 : " + m.add(Math4.a, Math4.b));		
        	//m.add(m.a, m.b) 하면 버그남(m에 노란줄 뜬다.)
        	//m.add(Math4.a, Math4.b)에는 (Math4.a, Math4.b)가 아닌 값만 전달된다.
		System.out.println("호출 후 a : " + Math4.a + ", b : " + Math4.b);

	}

}

 

 

 

 

 

 

 

 

 

 

 

** 실습 **

/* 8(1110수업)
 * 
문제)위와 동일하게 정수배열 5행 5열로 정의 한 후 1부터 1씩 증가해서 값을 채운 후 아래와
같이 출력하는 프로그램.(단 출력형식으로 배열에 저장)
단, 배열에 저장시만 1씩 증가하는 순서로 배열에 저장.
출력예) 1  2  3  4  5
 10  9  8  7  6
 11 12 13 14 15
 20 19 18 17 16
 21 22 23 24 25
 */

		int[][] arr = new int[5][5];
		int i, j, k = 1;
		
		for(i = 0 ; i < arr.length ; i++)
		{
			
			if(i % 2 == 0)
			{
				for(j = 0 ; j < arr[i].length ; j++)
				{
					arr[i][j] = k;
					k++;
					
				}
			}
			else
			{
				for(j = arr[i].length-1 ; j >= 0 ; j--)
				{
					arr[i][j] = k;
					k++;
					
				}
			}
		}
		
			for(i = 0 ; i <arr.length ; i++)
		{
			for(j = 0 ; j < arr.length ; j++)
			{
				System.out.printf("%3d", arr[i][j]);
			}
			System.out.println();
		}

** 실습2 **

/* 1
 문제)4행4열인 2차원 배열을 만들고 1~10까지 정수를 10개 랜덤하게 생성해 임의의 차례로 삽입하고
  납은 6개의 수는 모두 0으로 채워 넣습니다.
  단, 동일한 정수가 있어도 상관없고 만들어진 2차원 배열을 화면에 출력.
  랜덤 값은 0~10사이로 (int)(Math.random()*10 + 1) 사용. //1~10
  6개 0을 넣을 위치는 (int)(Math.random()*4)사용. //4생4열이므로 0~3
  출력시 printf(%2d ", 변수) 사용
 출력예) 0 6 0 5
     0 8 0 7 
     8 0 0 5
     4 1 3 2
 */

			int[][] a = new int[4][4];
			int i, j, z;
			
			//정수를 랜덤하게 생성해서 저장
			for(i = 0 ; i < a.length ; i++)
			{
				for(j = 0 ; j < a[i].length ; j++)
				{
					a[i][j] = (int)(Math.random()*10 + 1);
				}
			}
			
			//6개의 랜덤 위치에 0으로 넣어주기
			for(z = 0 ; z < 6 ; z++)
			{
				i = (int)(java.lang.Math.random()*4); //오류날 경우 java.lang 넣어주기
				j = (int)(Math.random()*4);
				if(a[i][j] == 0)
				{
					z--;
					continue;
				}
				a[i][j] = 0;
			}
			//(다른방법)6개의 랜덤 위치에 0으로 넣어주기
			while(z < 7)
			{
				i = (int)(java.lang.Math.random()*4);
				j = (int)(Math.random()*4);
				
				if(a[i][j] != 0)
				{
					a[i][j] = 0;
					z++;
				}
			}
			
			//배열출력
			for(i = 0 ; i < a.length ; i++)
			{
				for(j = 0 ; j < a[i].length ; j++)
				{
					System.out.printf("%2d ", a[i][j]);
				}
				System.out.println();
			}



 

** 객체지향언어 **

 

프로그램을 객체단위로 나누어서 객체를 중심으로 프로그램을 구성하는 언어.

객체단위로  구현하며 예를 들면 사람, 동물, 자동차 등... 단위로 구현.

 

- 특징 : 캡슐과, 다형성, 상속성

1. 코드의 재사용성 : 기존 코드를 이용하여 쉽게 작성한다. (상속성)

2. 코드의 관리 용이 : 코드간의 관계를 이용하여 쉽게 코드 변경 (다형성과 메소드의 오버로딩)

3. 신뢰성이 높은 프로그래밍 가능 : 데이터 보호하고 올바른 값 유지 (캡슐화와 데이터 은닉화)

장점 : 코드의 재사용성이 높고 유지보수가 용이함

 

Tv t = new Tv(); Tv클래스를 객체생성(new Tv())해서 인스턴스t로 객체를 바라보게했다. new를 통해

 

** 클래스와 객체 **

 

클래스 - 객체를 만들어 내기 위한 설계도 혹은 틀

              연관되어 있는 변수와 메서드의 집합

 

객체 - 소프트위어 세계에 구현할 대상

          클래스에 선언된 모양 그대로 생성된 실체

          클래스의 인스턴스(instance)라고도 함

          객체는 모든 인스턴스를 대표한는 포괄적 의미

          클래스의 타입으로 선언되었을때 객체라고 함 

 

인스턴스 - 객체가 메모리에 할당되어 실제 사용될때 인스턴스라고 한다.

                  객체는 클래스의 인스턴스

 

클래스는 설계도, 객체는 설계도로 구현한 모든 대상

클래스의 타입으로 선언되었을때 객체라고 부르고, 그 객체가 메모리에 할당되어 실제 사용될때 인스턴스라고 함

 

- 객체의 구성요소

  · 속성(property) : 멤버변수(member variable)

                              특성 (attribute)

                              필드 (field)

                              상태 (state)

  · 기능(function) : 메서드 (method)

                              함수 (function)

                              행위 (behavior)

 

객체 구성요소  
속성(property)  
기능(function)  

 

 

- 변수와 메서드 (클래스는 변수와 메서드로 이루어져있다.)

종류 선언위치 생성시기
클래스 변수 (static 있으면 클래스변수) 클래스 영역 클래스가 메모리에 올라갈때
별도의 객체생성 없이 사용가능
인스턴스변수 (반드시 객체생성 후 사용가능) 클래스 영역 인스턴스가 생성되었을때 (new)
지역 변수 (메소드 안에서만 사용가능) 메서드, 생성자, 초기화 블록내부 변수 언어문이 수행될때

 

 

- example)

class MySample{
				int iv;			//인스턴스변수
				static int cv;		//클래스변수
				
				void method() 
				{
					int iv = 0;	//지역변수
				}
			}
            
            		//다른 집
			s.iv
			a.iv
			
			//같은 집
			s.cv
			a.cv

 

java에서 static 있으면 new가 필요 없다.

 

** 메서드 **

 

- 특정 작업을 수행하는 일려느이 문장들을 하나로 묶은 것을 의미함.

- 메서드 사용 이유

  1. 높은 재사용성

  2. 중복된 코드 제거

  3. 프로그램의 구조화

 

반환타입 메서드이름(타입 변수명, 타입 변수명, ...){   선언 구현부   }  → 선언구현부 한줄밖에 없어도 {} 꼭 써야한다.

                                             매개변수

메서드 이름 - (소문자 시작, 두번째단어는 대문자) 

 

반환타입이 없을경우 void 를 사용해줘야한다.

 

example)

int add(int a, int b)	//선언부
{
	int result = a + b;	//구현부
	returm result;
}

 

 


public class MySample1113_2 {
	
	//클래스
	int iv;				//인스턴스 변수
	static int cv;		//클래스 변수

	int methodA(int k)	//지역 변수k -> methodA 메서드에서만 쓰는 k변수
	{
		int lv = 5;		//지역변수 lv, a
		k = k + lv;
		System.out.println("methodA() lv : " + lv);
		System.out.println("methodA() a : " + k);
		
		return k;
	}
	
	public static void main(String[] args) {
		
		MySample1113_2 a = new MySample1113_2();
		MySample1113_2 b = new MySample1113_2();
		MySample1113_2 c = new MySample1113_2();
		
		System.out.println("before a.iv : " + a.iv + ", b.iv : " + b.iv + ", c.iv : " + c.iv);
		
		//서로 다른 집의 iv
		a.iv = 10;
		b.iv = 20;
		c.iv = 30;
		
		System.out.println("after a.iv : " + a.iv + ", b.iv : " + b.iv + ", c.iv : " + c.iv);
		
		a.cv = 11;
		b.cv = 22;
		c.cv = 33;
		
		System.out.println("after a.cv : " + a.cv + ", b.cv : " + b.cv + ", c.cv : " + c.cv);
		
		System.out.println("1 MySample1113_2.cv : " + MySample1113_2.cv);
		
		MySample1113_2.cv = 55;
		
		System.out.println("after a.cv : " + a.cv + ", b.cv : " + b.cv + ", c.cv : " + c.cv);
		
		System.out.println("1 MySample1113_2.cv : " + MySample1113_2.cv);
		
		
		
		//메서드 호출
		int k = 60;		//지역 변수 k -> main 메서드에서만 쓰는 k변수 -> methodA에서 쓴는 변수 k랑은 이름만 같을 뿐
		a.methodA(50);
		
		System.out.println("main() method() 호출 전 k : " + k);
		
		b.methodA(k);
		
		System.out.println("main() method() 호출 후 k : " + k);
		System.out.println("main() method() 호출 후 바로 반환 : " + b.methodA(k));
//		c.methodA(k + 30);
		
		
		
		int a1 = 10;
		
	}

}

class Tv
{
	//인스턴스 변수(클래스에서 선언된 변수는 모든곳에서 사용가능)
	String color;		//tv색상
	boolean power;		//전원상태(on/off)
	int channel;		//채널
	
	//메서드
	void power()
	{
		power = !power;
	}
	
	void channelUp()
	{
		channel++;
	}
	
	void channelDown()
	{
		channel--;
	}
	
}

public class MySample1113_3 {

	public static void main(String[] args) {
		
		//클래스
		Tv t = new Tv();	//객체선언
		t.channel = 11;		//변수
		t.channelDown();	//메서드
		t.channelUp();
		System.out.println("현재 채널은 " + t.channel + " 입니다.");
		
		//현재 채널 11에서 7번으로 변경 설정.
		t.power();
		t.color = "검정";
		
		for(int i = t.channel ; i > 7 ; i--)
		{
			t.channelDown();
		}
		
		System.out.printf("tv전원은 %b 이고, 색상은 %s, 채널은 %d 입니다.\n",
        					t.power, t.color, t.channel);

		//------------------------------------------------------------------------------------
		
		/* 1
		 실행결과)t1의 channel값은 0입니다.
		 	   t2의 channel값은 0입니다.
		 	   t1의 channel값을 7로 변경했습니다.
		 	   t1의 channel값은 7입니다.
		 	   t2의 channel값은 7입니다.	//참조형 대입으로 처리
		 */
		
		Tv t1, t2;
		t1 = new Tv();
		t2 = new Tv();
		
//		Tv t1 = new Tv();	//위와 같음
//		Tv t2 = new Tv();
		
		t1.channel = 0;
		t2.channel = 0;
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다.");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다.");
		
		for(int i = t1.channel ; i < 7 ; i++)
		{
			t1.channelUp();
		}
		System.out.println("t1의 channel값을 " + t1.channel + "로 변경했습니다.");
		
		t2 = t1;
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다.");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다.");
        
        //------------------------------------------------------------------------------------
        
        		/* 2
		 실행결과)t1의 channel값은 0입니다.
		 	   t2의 channel값은 0입니다.
		 	   t1의 channel값을 5로 변경했습니다.	//변수에 값대입하여 적용
		 	   t2의 channel값을 11로 변경했습니다.	//변수에 값대입하여 적용
		 	   t1의 channel값은 11입니다.
		 	   t2의 channel값은 11입니다.
		 */
		
		Tv t1 = new Tv();
		Tv t2 = new Tv();
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다.");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다.");
		
		t1.channel = 5;
		t2.channel = 11;
		
		System.out.println("t1의 channel값을 " + t1.channel + "변경했습니다.");
		System.out.println("t2의 channel값을 " + t2.channel + "변경했습니다.");
		
		t1 = t2;
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다.");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다.");
	}
}

** 객체 배열 **

		//------------------------------------------------------------------------------------------------
		
		//객체 배열
		
		Tv[] t1 = new Tv[3];	//객체생성 아직안됨, 객체생성은 이름() 이렇게해야함
		int i;
		
		for(i = 0 ; i < t1.length ; i++)
		{
			t1[i] = new Tv();	//각각 Tv 시작 주솟값을 t1[i]배열에 각각대입
			t1[i].channel = i + 10;
			
			System.out.printf("전 t1[%d], channel1 = %d \n", i, t1[i].channel);
		}
		
		System.out.println();
		
		for(i = 0 ; i < t1.length ; i++)
		{
			t1[i].channelUp();
			System.out.printf("후 t1[%d].channel = %d \n", i, t1[i].channel);
		}
		
		
		//객체배열 복사 응용
		System.out.println("t1 : " + t1);			//t1[0]의 주소값 (실제 윈도우 주소는 X)
		System.out.println("t1[0] : " + t1[0]);		//new Tv()했을 때 객체생성한 주소값
		System.out.println("t1[1] : " + t1[1]);
		System.out.println("t1[2] : " + t1[2]);

		Tv a = new Tv();
		
		System.out.println("a : " + a);
		
		a = t1[1];
		
		System.out.println("후 a : " + a);
		
		System.out.println("a.channel : " + a.channel + ", t1[1].channel : " + t1[1].channel);
		
		a.channel = 20;
		
		System.out.println("

class Tv
{
	//참조형 변수를 활용한 예제 샘플용
	void channelTest(Tv a)		//참조형(주소)
	{
		System.out.println("Tv channelTest() a.channel : " + a.channel);
		a.channel = 20;
		System.out.println("후 Tv channelTest() a.channel : " + a.channel);
	}
	
	void channelTest2(int ch)	//기본형(값)
	{
		System.out.println("Tv channelTest2() ch : " + ch);
		ch = 20;
		System.out.println("후 Tv channelTest2() ch : " + ch);
	}
	
}


public class MySample1113_3 {

	public static void main(String[] args) {
		
        //참조형 변수로 활용한 예제
		
		Tv z = new Tv();
		z.channel = 11;
		
		System.out.println("main() z.channel : " + z.channel);
		z.channelTest(z);
		System.out.println("후 main() z.channel : " + z.channel);
		
		System.out.println();
		System.out.println();
		
		int ch = 11;
		
		System.out.println("main() ch : " + ch);
		z.channelTest2(ch);
		System.out.println("후 main() ch : " + ch);
		

	}

}

 

 

 

 

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/15 수업(13회차) _ 매개 변수 예제/ 반환 타입 예제  (0) 2023.11.15
11/14 수업 (12일차)  (1) 2023.11.14
11/10 수업 (10일차)  (0) 2023.11.10
11/09 수업 (9일차)  (2) 2023.11.09
11/08 수업(8일차)  (0) 2023.11.08

** 실습1 **

/* 7
 문제)정수 5개를 입력받을 배열을 선언한 후 정수 5개를 입력받아 배열에 저장한 후 
   배열복사를 통해 크기가 2배인 배열에 복사하고 언래 배열 크기뒤부터 다시 입력 
   5개를 받아 출력하는 프로그램 작성.
   단, 추가 입력까지 모두 한 후에 배열 복사 진행.
 입력예)10 20 30 40 50 (arr에 입력)
 출력예)arr.length : 5 (arr로 출력)
    10 20 30 40 50 
 입력예)1 2 3 4 5   (tmp에 입력)
 배열복사 후 출력
 최종출력예)10 20 30 40 50 1 2 3 4 5 (arr로 출력)
 */

// * 참조형 변수는 초기값이 null로 세팅된다.*

		int[] arr = new int[5];
		int i;
		
		for(i = 0 ; i < arr.length ; i++)
		{
			arr[i] = scn.nextInt();
		}
		
		System.out.printf("arr. length : %d \n", arr.length);
		
		for(i = 0 ; i < arr.length ; i++)
		{
			System.out.printf("%d ", arr[i]);
		}
		
		int[] tmp = new int[arr.length * 2];
		
		for(i = 0 ; i < arr.length ; i++)
		{
			tmp[i] = arr[i];
		}
		
		for(i = arr.length ; i < tmp.length ; i++)
		{
			tmp[i] = scn.nextInt();
		}
		
       		//배열 복사
		arr = tmp;
		
		System.out.println("arr.length ; " + arr.length);
		
		for(i = 0 ; i < arr.length ; i++)
		{
			System.out.printf("%d ", arr[i]);
		}

 


** 실습2 (랜덤) **

		//* 2 랜덤 Math.random()		//double형으로 0.0이상 1.0미만 사이 값 반환
		//실행결과)012345789
		//		582164930(결과-랜덤)
		
		int[] arr = new int[10];
		int i, n, tmp;
		
		for(i = 0 ; i < arr.length ; i++)
		{
			arr[i] = i;
			System.out.print(arr[i]);
		}
		
		System.out.println();
		
		for(i = 0 ; i < 100 ; i++)
		{
			n = (int)(Math.random() * 10); 		//0~9사이 하나의 값
			//Math = 클래스, .random = 메소드 / (int)강제형변환 
			
			System.out.printf("%d ", n);
			
			tmp = arr[0];
			arr[0] = arr[n];
			arr[n] = tmp;
		}
		
		System.out.println();
		
		for(i = 0 ; i < arr.length ; i++)
		{
			System.out.printf("%d", arr[i]);
		}

** 실습3 **

/* 3
 문제)로또번호 발생기
   배열에 1부터 45까지 값을 저장한 후에 0번째와 random 배경의 값을 바꾸는데 
   횟수를 100번 실행하고 최종 로또번호는 앞에서부터 6개 출력(배열에 0~5번째 값)
   단, (int)(Math.random() * 45) //0~44사이 값중 한 값 생성  
 */

		int[] arr = new int[45];
		int i, n, tmp;
		
		for(i = 0 ; i < arr.length ; i++)
		{
			arr[i] = i + 1;
		}
		
		for(i = 0 ; i < 100 ; i++)
		{
			n = (int)(Math.random() * 45);
			tmp = arr[0];
			arr[0] = arr[n];
			arr[n] = tmp;
		}
		
		for(i = 0 ; i < 6 ; i++)
		{
			System.out.printf("%d ", arr[i]);
		}



 

**  String클래스 (참조형) **

 

- 문자배열인 char배열과 같은 의미 (char : 한칸한칸 문자저장 / String : 한칸에 문자열 저장)

- char 배열이 아닌 String클래스를 이용해서 문자열을 처리하는 이유

   : String클래스가 char배열에 기능(메서드)를 추가한 것이기 때문임

- char배열과 String클래스의 중요한 차이는 String객체는 읽을 수만 있을 뿐 내용을 변경할 수 없음.(StringBuffer 클래스 사용)

 

ex) char[] a = new char[5];

       a[0] = 'A';

       a[1] = 'B';

       a[3] = 'C';

 

       와

 

      String b = "ABC";

 

       결과 값은 같다

 

char[] a = new char[5];

a[0] = 'A';

a[1] = 'B';
a[3] = 'C';
String b = "ABC"; 결과값 동일

 

String a = "abc";
a = "abcde"
읽을 수는 있지만 주소값이 서로 다르기 때문에 바뀌는건 아니다. 
내부적으로 배열 복사가 일어난다.

 

String str = "Java:;

str = str + "8";                    //"Java8" 이라는 새로운 문자열이 str에 저장

System.out.println(str);      // "Java8"

문자열 str의 내용이 변경되는 것 같지만, 문자열은 변경할 수 없으므로 새로운 내용의 문자열이 생성됨.

(자료가 잘 변경되는 것에 String을 잘 사용하지 않는 이유)

 

 

* String 클래스의 중요 메서드 *

메서드 설명
char charAt(int index) 문자열에서 해당위치(index)에 있는 문자를 반환한다.
int length() 문자열의 길이를 반환한다.
String substring(int from, int to) 문자열에서 해당범위(from~to)에 있는 문자열을 반환한다
(to는 범위에 포함되지 않음)
boolean equals(Object obj) 문자열의 내용이 obj와 같은지 확인한다.
같으면  true / 다르면 flase
메서드 앞의 boolean : 반환 타입
char[] toCharArray[] 문자열을 문자배열(char[])로 변환해서 반환함

 

 

* String 배열 *

 - 3개의 문자열을 담을 수 있는 배열생성

 

 String[] name = new String[3];

 

String[] name = new String[3];

String[] name = new String[3];

neame[0] = new String("Kim");
neame[2] = new String("Park");
neame[3] = new String("Yu");
String[] name = new String[3];

neame[0] = "Kim"
neame[1] = "Park"
neame[2] = "Yu"

 

 

 

 

 


** String 클래스 **

		//String 클래스
		
		String str = "java programing";
		char c = str.charAt(0);			//String클래스의 charAt(인덱스값)메서드
		char[] ch = {'j','a','v','a'};	//배열
		
		System.out.println("str.charAt(0) : " + c);
		System.out.println("str.charAt(5) : " + str.charAt(5));
		
		System.out.println("str.length() : " + str.length());			//-> str.length() : 15
		System.out.println("str.substring() : " + str.substring(3));	//-> str.substring() : a programing
		System.out.println("str.substring() : " + str.substring(1, 8));	//-> str.substring() : ava pro
		System.out.println("str.equals(1) : " + str.equals("java programing"));	//-> str.equals(1) : true
		System.out.println("str.equals(2) : " + str.equals("java"));			//-> str.equals(2) : false
		
		
		int num = 10;
		
		String str1 = String.valueOf(num);
		System.out.println(str1 + ", length : " + str1.length());		//-> 10, length : 2

* String 배열 *

		//String 배열
		String[] names = {"kim", "park", "lee"};
		String name = "kimparklee";
		int i;
		
		for (i = 0 ; i < names.length ; i++)
		{
			System.out.println("names[" + i + "] : " + names[i]);
		}
		
		String tmp = names[2];
		System.out.println("tmp : " + tmp);
		names[0] = "yu";
		
		for (i = 0 ; i < names.length ; i++)
		{
			System.out.println("names[" + i + "] : " + names[i]);
		}
		
		//names[0] - kim, yu 가 가리키는 주소는 다르다.

 

// char배열과 String클래스 변환

		//char배열과 String클래스 변환
		String str = "ABCDE";
		int i;
		char ch;
		
		for(i = 0 ; i < str.length() ; i++)
		{
			ch = str.charAt(i);
			System.out.println("str.charAt(" + i + ") : " + ch);
		}
		
		//String을 char[]로 변환
		char[] chArr = str.toCharArray();
		System.out.println(chArr + ", length : " + chArr.length);

 


** 다차원 배열 **

선언 방법 선언 예
타입[][] 변수이름; int[][] score;
타입 변수이름[][]; int score[][];
타입[] 변수이릅[];  //잘 사용 안함 int[] score[];

 

int[][] score = new int[4][3];       // 4행 3열의 2차원 배열

score[0][0] score[0][1] score[0][2]
score[1][0] score[1][1] score[1][2]
score[2][0] score[2][1] score[2][2]
score[3][0] score[3][1] score[3][2]

 

- 2 차원 배열 초기화

int[][] arr = new int[][]{{1, 2, 3}, {4, 5, 6}};

int[][] arr = {{1, 2, 3}, {4, 5, 6}};

 

 

 


* 2차원배열(다차원 배열)
/* 4 2차원 배열의 초기화 설정은 한 후 실행
 실행결과)score[0][0] = 100
      score[0][1] = 100
      score[0][2] = 100
      score[1][0] = 20
      score[1][1] = 20
      score[1][2] = 20
      score[2][0] = 30
      score[2][1] = 30
      score[2][2] = 30
      score[3][0] = 40
      score[3][1] = 40
      score[3][2] = 40
      sum = 570
 */

		int[][] score = new int[][] {{100, 100, 100},{20, 20, 20},{30, 30, 30},{40, 40, 40}};
		int i, j, sum = 0;
		
		for(i = 0 ; i < score.length ; i++)
		{
			for(j = 0 ; j < score[i].length ; j++)
			{
				System.out.printf("score[%d][%d] = %d \n", i, j, score[i][j]);
				sum += score[i][j];
			}
		}
		
		System.out.println("sun = " + sum);

** 실습5 **

/* 5
 문제)String배열을 이용한 단어 맞추기.
   배열에 "chair", "의자"
      "computer", "컴퓨터"
      "integer", "정수"로 선언
 입.출력예)chair의 뜻은>책상
   틀력습니다. 정답은 의자입니다.
   
   computer의 뜻은?컴퓨터
   정답입니다.
   
   integer의 뜻은?정수
   정답입니다.
 단, 문자연 비교는 equals 매서드 사용.(예 : a.equals("의자"))
  equals 메서드의 인수값을 2차원 배열로 표현
 */

		String[][] words = {{"chair", "의자"},{"computer", "컴퓨터"},{"integer", "정수"}};
		int i, j;
		String w;
		
		for(i = 0 ; i < words.length ; i++)
		{
			System.out.printf("%s의 뜻은?", words[i][0]);
			w = scn.nextLine();
			
			if(w.equals(words[i][1])) 
			{
				System.out.println("정답입니다.");
			}
			else
				System.out.println("틀렸습니다. 정답은 " + words[i][1] + "입니다.");
		}

** 실습6 **

/* 6
 문제)5명의 학생의 3과목 점수를 더해서 각 학생의 총점과 평균을 계산하고,
 과목별 총점을 계산하는 프로그램 작성.
 단, 과목은 score 2차원배열에 저장하고 출력시 번호는 %3d, 각 점수는 %5d, 평균은 %5.1f 적용 // 소숫점밑 1자리와 소숫점을 포함한 5자리
 실행결과)번호   국어   영어   수학   총점   평균
     ===================================
       1   100   100   100   300   100.0
       2    20    20    20    60    20.0
       3    30    30    30    90    30.0
       4    40    40    40   120    40.0
       5    50    50    50   150    50.0
     ===================================
      총점  240   240   240
 */

		int[][] score = {{100, 100, 100},{20, 20, 20},{30, 30, 30},{40, 40, 40},{50, 50, 50}};
		
		int sum , i, j;
		int totalKor = 0, totalEng = 0, totalMath = 0;
		double avg;
		
		System.out.println(" 번호   국어   영어   수학   총점   평균");
		System.out.println("===================================");
		for(i = 0 ; i < score.length ; i++)
		{
			System.out.printf("  %d ", i+1);
			
			sum=0;
			for(j = 0 ; j < score[i].length ; j++)
			{	
				sum += score[i][j];
				System.out.printf("%5d ", score[i][j]);
			}
			
			totalKor += score[i][0];
			totalEng += score[i][1];
			totalMath += score[i][2];
			
			avg = (double)sum/score[i].length;
			System.out.printf("%5d  %5.1f ", sum, avg);
			System.out.println();
		}
		
		System.out.println("===================================");	
		System.out.printf(" 총점%5d %5d %5d", totalKor, totalEng, totalMath);

** 실습7 **

/* 7
 문제)정수 배열 5행 5열로 선언한 후 각 배열 위치에 1로 시작해서 1씩 증가하는 값을 
   저장한 후 5행 5열을 출력하는 프로그램
 출력예) 1 2 3 4 5
     6 7 8 9 10
     11 12 13 14 15
     16 17 18 19 20
     21 22 23 24 25
 */

		int[][] arr = new int[5][5];
		int i, j, k = 1;
		
		for(i = 0 ; i < arr.length ; i++)
		{
			for(j = 0 ; j < arr[i].length ; j++)
			{
				arr[i][j] = k;
				k++;
				System.out.printf("%-3d ", arr[i][j]);
			}
			System.out.println();
		}

** 실습8 **

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/14 수업 (12일차)  (1) 2023.11.14
11/13 수업 (11일차)  (2) 2023.11.13
11/09 수업 (9일차)  (2) 2023.11.09
11/08 수업(8일차)  (0) 2023.11.08
11/07 수업 (7일차)  (1) 2023.11.07

** 실습1 **

/* 1 배열
 문제)5개의 정수를 {95, 75, 85, 100, 50}으로 초기화 하고 오름차순으로 정렬하여 출력하는 프로그램
 출력예)50 75 85 95 100
 */

		int[] arr = {95, 75, 85, 100, 50};
		int i, j, tmp;
		
		for(i = 0 ; i < arr.length-1 ; i++)
		{
			for(j = i + 1 ; j < arr.length ; j++)
			{
				if(arr[i] > arr[j])
				{
					tmp = arr[i];
					arr[i] = arr[j];
					arr[j] = tmp;
				}
			}
		}
		
		for(i = 0 ; i < arr.length ; i++)
		{
			System.out.printf("%d ", arr[i]);
		}

** 실습2 **

/* 2
 문제)10개의 정수를 입력받아 배열에 저장할 후 내림차순으로 정렬하는 프로그램.
 입력예)95 100 88 65 76 89 58 93 77 99
 출력예)100 99 95 93 89 88 77 76 65 58
 */

		int[] a = new int[10];
		int i, j, tmp;
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
		}
		
		for(i = 0 ; i < a.length-1 ; i++)
		{
			for(j = i + 1 ; j < a.length ; j++)
			{
				if(a[i] < a[j])
				{
					tmp = a[i];
					a[i] = a[j];
					a[j] = tmp;
				}
			}
		}		
		for(i = 0 ; i < a.length ; i++)
		{
			System.out.printf("%d ",a[i]);
		}
		//바로위 for문을 정식 선택알고리즘으로 변경
		int val, idx = 0;	//val변수는 기준값 저장, idx변수는 교환할 j인덱스값 저장
		for(i = 0 ; i < a.length-1 ; i++)
		{			
			val = a[i];
			for(j = i+1 ; j < a.length ;j++)		// 100 95 88 65 76 89 58 93 77 99
			{
				if(val < a[j])
				{
					val = a[j];
					idx = j;
				}
			}
			
			//최종 자리교환		
			if(idx > i)
			{
				tmp = a[i];
				a[i] = a[idx];
				a[idx] = tmp;
			}
			
			//디버깅 
			System.out.println("i : " + i + ", idx : " + idx);
			for(int k = 0 ; k < a.length ; k++) 
			{
				System.out.printf("%d ", a[k]);
			}
			
			System.out.println();
			
			idx = i; 	//0;	//초기화 꼭 해야한다.
		}
		
		System.out.println();
		
		for(i = 0 ; i < a.length ; i++)
		{
			System.out.printf("%d ",a[i]);
		}

 

** 실습3 **

/* 3
 문제)최대 100개 정수를 입력받다가 0 이 입력되면 종료하고 그때까지 입력된 수 중 
   5의 배수의 개수와 합계, 평균을 출력하는 프로그램
 입력예)35 10 23 100 64 51 5 0
 출력예)5의 배수 : 4개
    합계 : 150
    평균 : 37.5
 */

		int[] a = new int[100];
		int i, cnt = 0, sum = 0;
		double avg;
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
			
			if(a[i] == 0)
				break;
			
			if (a[i] % 5 == 0)
			{				
				cnt++;
				sum += a[i];
			}
		}
		
		avg = (double)sum / cnt;
		
		System.out.printf("5의 배수 : %d개\n", cnt);
		System.out.printf("합계 : %d\n", sum);
		System.out.printf("평균 : %.1f", avg);
		//위에 for문을 for2개로 나누어 처리
		
		int num = 0;
		for( i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
			if(a[i] == 0)
				break;
			num++;
		}
		for(i = 0 ; i < num ; i++)
		{
			if(a[i] % 5 == 0)
			{
				sum += a[i];
				cnt++;
			}
		}
			
		
		avg = (double)sum / cnt;
		
		System.out.printf("5의 배수 : %d개\n", cnt);
		System.out.printf("합계 : %d\n", sum);
		System.out.printf("평균 : %.1f", avg);

** 실습4 **

/* 4
 문제)100개 이하의 정수를 입력받다가 0이 입력되면 0을 제외하고 그때까지 입력방은
   개수를 출력한 후 입력 받은 정수를 차례로 출력하되 그 수가 홀수이며 2배한 값을
   짝수이면 2로 나눈 몫을 출력하는 프로그램.
   단, 값 출력은 배열을 이용하지 않음.(배열의 입력값은 변경 없음.)
 입력예)8 10 5 15 100 0
 출력예)5
    4 5 10 30 50 
 */

		int[] arr = new int[100];
		int i, cnt = 0;
		
		
		for(i = 0 ; i < arr.length ; i++)
		{
			arr[i] = scn.nextInt();
			
			if(arr[i] == 0) break;
			
			cnt++;
		}
		
		System.out.println(cnt);
		int val;
		
		for(i = 0 ; i < cnt ; i++)
		{
			if(arr[i] % 2 == 0)
			{
				val = arr[i] / 2;
			}
			else
				val = arr[i] * 2;
			
				System.out.printf("%d ", val);
		}
		//위와 동일한 결과로 for문 1번만 사용경우 출력결과 순서변경
		
		int tmp;
		for(i = 0 ; i < arr.length ; i++)
		{
			arr[i] = scn.nextInt();
			
			if(arr[i] == 0) 
			{
				System.out.println("\n" + cnt);
				break;
			}
			
			cnt++;
			
			if(arr[i] % 2 == 0)
				tmp = arr[i] / 2;
			else
				tmp = arr[i] * 2;
			
			System.out.print(tmp + " ");
		}

** 실습5 **

/* 5
 문제)정수 10개를 입력받아 최대 값을 출력하는 프로그램 작성.
   단, 변수는 배열변수 score와 출력용 max, for문용 i만을 선언함.
     정수는 0~100사이 값만 입력받으며 나머지 값 입력시
     "숫자의 범위가 초과 되었습니다."
     "0~100사이의 숫자를 다시 입력하세요.>"
 입력예)110
    숫자의 범위가 초과 되었습니다.
    0~100사이의 숫자를 다시 입력하세요.>
 입력예)95 67 88 65 76 89 58 93 77 99 (입력시마다 하나의 값 입력 후 바로 엔터)
 출력예)가장 큰 값은 99입니다.
 */

//for문 1번만 사용할 경우
		
		int[] a = new int[10];
		int max = 0, i;
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
			
			if(a[i] < 0 || a[i] > 100)
			{
				System.out.println("숫자의 범위가 초과 되었습니다.");
				System.out.print("0~100사이의 숫자를 다시 입력하세요.>");
				i--;
				continue;
			}
			
			if(a[i] > max)
			{
				max = a[i];
			}
		}
		
		System.out.printf("가장 큰 값은 %d입니다.\n", max);
		//while문 사용한 풀이 (for문 2개)
		
		int[] a = new int[10];
		int max = 0, i;
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
			
			while(a[i] < 0 || a[i] > 100)
			{
				System.out.println("숫자의 범위가 초과 되었습니다.");
				System.out.print("0~100사이의 숫자를 다시 입력하세요.>");
				a[i] = scn.nextInt();
			}
		} 
		
		max = a[0];
		for(i = 1 ; i < a.length ; i++)
		{
			if(max < a[i])
			{
				max = a[i];
			}
		}
		
		System.out.printf("가장 큰 값은 %d입니다.\n", max);
		//if 사용 (for문 2개)
		
		int[] a = new int[10];
		int max = 0, i;
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
			
			if(a[i] < 0 || a[i] > 100)
			{
				System.out.println("숫자의 범위가 초과 되었습니다.");
				System.out.print("0~100사이의 숫자를 다시 입력하세요.>");
				i--;
				continue;
			}
		}
		
		max = a[0];
		for(i = 1 ; i < a.length ; i++)
		{
			if(max < a[i])
			{
				max = a[i];
			}
		}
		
		System.out.printf("가장 큰 값은 %d입니다.\n", max);

** 실습6 **

/* 6
 문제)20 이하의 정수 n을 입력받고 n명의 점수를 입력받아 높은 점수 부터 차례로 출력하는 프로그램
 입력예)5
      35 10 35 100 64
 출력예)100 64 35 35 10
 */

		int i, j, tmp;
		
		int n = scn.nextInt();
		
		int[] score = new int[n];
		
		for(i = 0 ; i < score.length ; i++)
		{
			score[i] = scn.nextInt();
		}
		
		for(i = 0 ; i < score.length-1 ; i++)
		{
			for( j = i + 1 ; j < score.length ; j++)
			{
				if(score[i] < score[j])
				{
					tmp = score[i];
					score[i] = score[j];
					score[j] = tmp;
				}
			}
		}
		
		for(i = 0 ; i < score.length ; i++)
		{
			System.out.print(score[i] + " ");
		}
		//정렬은 모두 받아두고 밖에서 정렬하는것이 제일 좋다.

** 실습7 **

/* 7
 문제)정수 5개를 입력받을 배열을 선언한 후 정수 5개를 입력받아 배열에 저장한 후 
   배열복사를 통해 크기가 2배인 배열에 복사하고 언래 배열 크기뒤부터 다시 입력 
   5개를 받아 출력하는 프로그램 작성.
   단, 추가 입력까지 모두 한 후에 배열 복사 진행.
 입력예)10 20 30 40 50 (arr에 입력)
 출력예)arr.length : 5 (arr로 출력)
    10 20 30 40 50 
 입력예)1 2 3 4 5   (tmp에 입력)
 배열복사 후 출력
 최종출력예)10 20 30 40 50 1 2 3 4 5 (arr로 출력)
 */

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/13 수업 (11일차)  (2) 2023.11.13
11/10 수업 (10일차)  (0) 2023.11.10
11/08 수업(8일차)  (0) 2023.11.08
11/07 수업 (7일차)  (1) 2023.11.07
11/06 수업 (6일차)  (0) 2023.11.06

** 실습1 **

/* 1
 문제)100개의 정수를 저장할수 있는 배열을 선언하고 차례대로 입력 받다가 0이 입력되면
   0을 제외하고 그때까지 입력된 정수를 가장 나중에 입력된 정수부터 차례대로 
   출력하는 프로그램.
 입력예)3 5 10 55 0
 출력예)55 10 5 3
 */

		int[] arr = new int[100];
		int i, cnt = 0;
		
		for(i = 0 ; i < arr.length ; i++)
		{
			arr[i] = scn.nextInt();			
			if(arr[i] == 0)
				break;
				
			cnt++;
		}
		for(i = cnt-1 ; i >= 0 ; i--)
		{
			System.out.print(arr[i] + " ");
		}
		
		//i변수 이용하여 반복 (위와 동일한 문제)
		int j;
		
		for(j = i-1 ; j >=0 ; j--)
		{
			System.out.printf("%d ", arr[j]);
		}

**  실습2 **

/* 2
 문제)연도와 월을 입력받아 해당 월의 날수를 출력하다가 월이 0이 입력되면 프로그램 종료
   (무한루프이용)
   단, 윤년은 400년에 한번씩, 4년에 한번이면서 100년은 제외.
    year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
    윤년인 경우 2월의 날수는 29일
 입.출력예)년 = 2000
  월 = 2
  입력하신 달의 날수 는 29일 입니다. //days[month]
 
  년 = 2022
  월 = 13
  잘못입력하셨습니다. //month 월을 1~12가 아닌 경우
 
  년 = 2023
  월 = 0
 */

		int[] days = {0,31,28,31,30,31,30,31,31,30,31,30,31};	//new int[13]
		int year, month;
		
		
		while(true)
		{
			System.out.print("년 = ");
			year = scn.nextInt();
			System.out.print("월 = ");
			month = scn.nextInt();
			
			
			if(month == 0)
				break;
			
			if(month > 12 || month <1)
			{
				System.out.println("잘못입력하셨습니다.");
				continue;
			}
			
			else
			{
				if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) 
				{
					days[2] = 29;
				}
				else
				{
					days[2] = 28;
				}
				System.out.printf("입력사하신 달의 일수는 %d입니다.\n", days[month]);
			}
			
		}

** 실습3 **

/* 3
 문제)10개의 정수를 입력받아 그 중 가장 큰 수를 출력하는 프로그램
   단, 출력은 max변수 사용
 입력예)5 10 8 55 6 31 12 24 61 2
 출력예)61
 */

		int[] a = new int[10];
		int i,max=0;
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
			
			if(a[i] > max)	
			{
				max = a[i];
			}
		}
		
		System.out.print(max);
		//for문 2번 사용할 경우
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
		}

		max = a[0];
		
		for(i = 1 ; i < a.length ; i++)
		{
			if(max < a[i])
			{
				max = a[i];
			}
		}

** 실습4 **

/*
 문제)10개의 수를 입력받아 그 중 가장 작은 수를 출력하는 프로그램
   단, 가장 작은 수 출력시 min변수를 사용하며, 선언시 초기값 설정하지 않음.
 입력예)5 -10 8 55 -6 31 12 24 61 -2
 출력예)-10
 */

		int[] a = new int[10];
		int i, min;
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
		}
		min = a[0];
		for(i = 1 ; i < a.length ; i++)
		{
			if(min > a[i])
			{
				min = a[i];
			}
		}
		
		System.out.println(min);

** 실습5 **

/* 5
 문제)4자리 이하의 10개 정수를 입력받아 짝수 중 가장 큰 값과 홀수중 가장 작은 값을
     출력하는 프로그램.
     단, min,max 변수 초기값 설정 후 진행함
 입력예)-5 10 -8 55 6 -31 12 -24 61 2
 출력예)홀수 중 가장 작은 값 : -1 (min)
    짝수중 가장 큰 값 : 12 (max)
 */

		int[] a = new int[10];
		int i, min = 9999, max = -9998; // min = 10000, max = -10000 가능
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
		}
		
		for(i = 0 ; i < a.length ; i++)
		{
			if(a[i] % 2 == 0)	//if(a[i] % 2 == 1)는 음수가 안된다.
			{	
				if(max <= a[i])
					max = a[i];
			}
			else
			{
				if(min >= a[i])
					min = a[i];
			}
		}

** 실습6 **

/* 6
 문제)10명의 컴퓨터 점수를 입력받아 배열에 저장하고 총점과 평균을 구하는 프로그램작성.
   단, for문 1번 사용. 평균은 소수 첫째자리까지 출력.
 입력예)95 100 88 65 80 89 58 93 77 99
 출력예)총점 = 844
    평균 = 84.4 
 */

		int[] score = new int[10];
		int i, sum = 0;	//누적하려면 초기화 해야한다.
		float avg;
		
		for(i = 0 ; i < score.length ; i++)
		{
			score[i] = scn.nextInt();
			sum += score[i];
		}
		
		avg = (float)sum / score.length;	//for문안에쓰려면 avg 초기화 해줘야한다.
        	// 정수 / 정수 는 정수이기에 둘중하나를 실수로 형변환해줘야한다.
		// foalt : 4byte / double : 8byte -> avg가 foalt이기에 double로 정수를 형변환하면 오류한다.  
		// 대입할때 큰평수에서 작은평수로는 대입 안된다.
		
		System.out.printf("총점 : %d \n", sum);
		System.out.printf("평균 : %.1f", avg);



 

** 정렬 **

 

** 선택정렬 (Selsection sort) **

   - 자료 중 가장 작은 값 / 가장 큰 값을 선택하여 맨앞 / 맨뒤 로 보내며 정렬하는 알고리즘

   - 비교 횟수는 많지만 교환 횟수가 적기 때문에 교환이 많이 이루어져야 하는 자료형태에서는 가장 효율적으로 적용가능                             

                                                                                                                                                                                                                              


** 선택정렬 **

/* 
 기본 배열 오름차순 정렬문제
 */                                                                                                                                                                                                                          

		int[] a = {3, 1, 2, 6, 5, 4};
		int i, j , tmp, k;
		
		for(i = 0 ; i < a.length-1 ; i++)
		{
			for(j = i + 1 ; j < a.length ; j++)
			{
				if(a[i] > a[j])
				{
					tmp = a[i];
					a[i] = a[j];
					a[j] = tmp;
				}
				
			}			
			System.out.println("\n" + i + "번째");
			for(k = 0 ; k < a.length ; k++)
			{
				System.out.printf("%d ", a[k]);
			}	
		}
		
		System.out.println("\n\n최종 실행후 결과");
		//디버깅 용도 : 프로그램문제는 없지만 내가 만든것을 검증하기위해?
		
		for(i = 0 ; i < a.length ; i++)
		{
			System.out.printf("%d ", a[i]);
		}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/10 수업 (10일차)  (0) 2023.11.10
11/09 수업 (9일차)  (2) 2023.11.09
11/07 수업 (7일차)  (1) 2023.11.07
11/06 수업 (6일차)  (0) 2023.11.06
11/02 수업 (4일차)  (0) 2023.11.05

** 실습1 **

/* 1 반복문
 문제)정수 n을 입력받아 n줄만큼 다음과 같이 출력하는 프로그램. (for문 사용)
   출력시 printf("%2d ",변수명)
   입력예)5
   출력예) 1
       2  3
       4  5  6
       7  8  9 10
      11 12 13 14 15
 */

		int n, i, j, cnt = 0;
		
		n = scn.nextInt();
		
		for(i = 1 ; i <= n ; i++)
		{
			for(j = 1 ; j <= i ; j++)
			{
				cnt++;
				System.out.printf("%2d ", cnt);
			}
			System.out.println();
		}

 


** 실습2 **

/* 2
 문제)정수 n을 입력받아 아래와 같이 영문자를 출력하는 프로그램.
 입력예)3
 출력예)ABC
    DE
    F
 */

		int n, i, j;
		char a = 'A';
		
		n = scn.nextInt();
		
		for(i = n ; i >= 1 ; i--)
		{
			for(j = i ; j >= 1 ; j--)
			{
				System.out.print(a + " ");
				a++;
			}
			System.out.println();
		}
        
        //-------------------------------------------------
        
        //다른방법
        	for(i = n ; i >= 1 ; i--)
		{
			for(j = 1 ; j <= i ; j++)
			{
				System.out.printf("%c ",a);
				a++;
			}
			System.out.println();
		}

** 실습3 **

/* 3
 문제)for문을 이용하여 다음과 같이 출력하는 프로그램 작성.
 출력예)a 1 2 3 4
    b c 5 6 7
    d e f 8 9
    g h i j 10
 4행 5열 고정으로 출력.
 */

		int num = 1;
		char alpha = 'a';
		int i, j;
		
		for(i = 1 ; i <= 4 ; i++)
		{
			for(j = 1 ; j <= i ; j++)
			{
				System.out.printf("%c ",alpha);
				alpha++;
			}			
			for(j = 4; j >= i ; j--)		//for(j = 1 ; j <= 5-i ; j++)
			{
				System.out.printf("%d ", num);
				num++;
			}
			System.out.println();
		}

** 실습4 **

/* 4
 문제)while문의 무한루프를 이용하여 아래와 같이 실행되는 프로그램 작성.
  (continue, break 사용)
 입.출력예)현재 가진 돈은 10000원 입니다.
  얼마를 사용하시겠습니까?1000
  이제 9000원 남았습니다.
 
  얼마를 사용하시겠습니까?5000
  이제 4000원 남았습니다.
 
  얼마를 사용하시겠습니까?5000
  다시 입력하세요.(사용범위오류)
 
  얼마를 사용하시겠습니까?4000
  이제 0원 남았습니다.
  모든돈을 사용했습니다. 끝
 */

		int money = 10000, n;
		
		System.out.println("현재 가진 돈은 " + money + "원 입니다.");
		
		
		while(true)
		{
			System.out.print("얼마를 사용하시겠습니까?");
			n = scn.nextInt();
			
			if(n >= 0 && n <= money)
			{
				money = money - n;
				System.out.printf("이제 %d원 남았습니다. \n", money);
			}
			else
			{
				System.out.println("다시 입력하세요.(사용범위오류)");
				continue;
			}
			if(money == 0)
			{
				System.out.println("모든돈을 사용했습니다. 끝");
				break;
			}
		}		
		
		//-------------------------------------------------------------------------------
		
		//다른풀이
		while(true)
		{
			System.out.print("얼마를 사용하시겠습니까?");
			n = scn.nextInt();
			
			if(n < 0 || n > money)
			{
				System.out.println("다시 입력하세요.(사용범위오류)");
				continue;
			}
			
			money = money - n;		//money -= n;
			System.out.printf("이제 %d원 남았습니다. \n", money);
			
			if(money == 0)
			{
				System.out.println("모든돈을 사용했습니다. 끝");
				break;
			}			
		}



 

** 배열 [] **

- 같은 타입의 여러 변수를 하나의 묶음으로 다루는 것을 의미함 / 데이터 탑입 - 참조형

  연속적으로 주소를 할당 받음

 

- 특징 : 선언과 동시에 사이즈를 정해줘야한다.

 

* 배열 선언과 생성

  타입[] 변수이름;       -> int[] score;

  타입 변수이름[];       -> int score[];

 

  int[] score;

  score = new int[5];          

 

  int[] score = new int[5]; 

 

* 배열의 인덱스는 0번부터 시작  score[0] score[1] score[2] score[3] score[4] 

 

* 배열에 배열명은 그 배열의 시작주소를 가리킨다.(꼭 외우기.)

 

cf) 자바 자료형 - 기본형 - 값

                         - 참조형 - 시작주소값

 

* 배열을 시작값과 length를 같이 가지고다닌다.


** 예제 **

 

//배열

/*
 5개의 정수를 입력 받은 후 차례대로 출력하는 프로그램
 */

/*
int a, b, c, d, e;

a = scn.nextInt();
b = scn.nextInt();
c = scn.nextInt();
d = scn.nextInt();
e = scn.nextInt();

Systehttp://m.out.printf("%d %d %d %d %d \n", a, b, c, d, e);
*/

//위 문제와 같은 것으로 배열을 사용하되 반복문은 사용하지 않음.

int[] a = new int[5];

a[0] = scn.nextInt();
a[1] = scn.nextInt();
a[2] = scn.nextInt();
a[3] = scn.nextInt();
a[4] = scn.nextInt();
a[5] = scn.nextInt();       //실행시 오류


Systehttp://m.out.printf("%d %d %d %d %d \n", a[0], a[1], a[2], a[3], a[4]);

//위 문제와 같은 것으로 배열을 반복문에 적용
int[] a = new int[5];
int i;

for(i = 0 ; i < a.length ; i++)
{
a[i] = scn.nextInt();
}

for(i = 0 ; i < a.length ; i++)
{
Systehttp://m.out.printf("a[%d] : %d \n", i, a[i]);
}

 


** 실습 5 **

/*
 문제)정수 5개를 입력 받은 후 합계를 출력하는 프로그램
 입력예)10 20 30 40 50
 출력예)150
 */

		int[] a = new int[5];
		int i, sum = 0;
		
		for(i = 0 ; i < a.length ; i++)	
		{
			a[i] = scn.nextInt();
			sum += a[i];
		}

		System.out.println(sum);

** 실습6 **

/* 6
 문제)문자 10개를 저장할수 있는 배열을 ㅇ선언하고 10개의 문자를 입력받아 입력받은 문자를 
     이어서 출력하는 프로그램
     단, scn.next().charAt(0); //공백을 기준으로 짤라 첫번째 글자만 반환
     next() : 공백 or 엔터를 기준으로 짤라서 문자열을 반환
     nextLine() : 전체 문자열 반환
     nextInt() : 공백 안자르고 숫자 반환
 입력예)A B C D E F G H I J
 출력예)ABCDEFGHIJ
 */

		char[] a = new char[10];
		int i;
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.next().charAt(0);		// 문자열을 char타입으로 바꿔줌
			System.out.printf("%c", a[i]);
		}

** 실습7 **

/* 7
 문제)정수 10개를 입력 받은 후 세번째, 다섯번째, 마지막으로 입력핟은 정수를 차례로 출력하는 프로그램
   단, 마지막 입력받은 값은 배열의 길이를 이용하여 출력.
 입력예)5 3 9 6 8 4 2 8 10 1
 출력예)9 8 1
 */

		int i;
		int[] a = new int[10];
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();
		}
		
		System.out.printf("%d %d %d \n", a[2], a[4], a[a.length - 1]);

** 실습8 **

/* 8
 문제)최대 100개 까지의 정수를 차례로 입력받다가 0 이 입력되면 입력을 중단하고 
   짝수번째에 입력된 정수를 모두 출력하는 프로그램작성
 입력예)11 25 3 9 0
 출력예)25 9
 */

		int i,j;
		int[] a = new int[100];
		
		for(i = 0 ; i < a.length ; i++)
		{
			a[i] = scn.nextInt();			
			if(a[i] == 0) 
				break;
		}
		
		for(j = 0 ; j < i ; j++)
		{
			if(j%2 == 1)
			{
				System.out.printf("%d ",a[j]);
			}
		}
		
		//다른풀이
		int i, cnt = 0;
		int[] a = new int[100];
		
		for(i = 0 ; i < a.length ; i++) 
		{
			a[i] = scn.nextInt();			
		
			if(a[i] == 0)
				break;
			cnt++;
		}
		for(i = 0 ; i < cnt ; i++)
		{
			if(i%2 == 1)
			{
				System.out.printf("%d ",a[i]);
			}
		}

** 실습9 **

/* 9
 문제)정수 5개를 입력받아 배열에 저장한 후 검색할 중수를 하나 입력받아 배열에 같은 
  값이 있는지 찾아 해당 위치의 인덱스를 출력하는 프로그램.
  단, 배열에 같은 수가 없을 경우 "일치하는 값이 존재하지 않습니다."
 입력예)입력 0 : 7
    입력 1 : 3
    입력 2 : 5
    입력 3 : 2
    입력 4 : 4
    찾을 값은 : 5
    일치하는 값의 인덱스는 : 2
    
    입력 0 : 3
    입력 1 : 8
    입력 2 : 5
    입력 3 : 6
    입력 4 : 1
    찾을 값은 : 7
    일치하는 값이 존재하지 않습니다.
 */

		int[] a = new int[5];	//배열선언
		int i, search; // searh:찾을값
		
		for(i = 0 ; i < a.length ; i++)
		{
			System.out.print("입력" + i + " : " );
			a[i] = scn.nextInt();
		}
		
		System.out.print("찾을 값은 : ");
		search = scn.nextInt();
		
		boolean flag = true;
		
		for(i = 0 ; i < a.length ; i++)
		{
			if(search == a[i])
			{
				System.out.println("일치하는 값의 인덱스는 : " + i);
				flag = false;
				break;
			}		
			//flag변수 사용안하고 for문에서 없을 경우 체크.
			//if(i == (arr.length-1) && search != arr[i])
		}
		
		if(flag)
		{
			System.out.println("일치하는 값이 존재하지 않습니다.");
		}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/09 수업 (9일차)  (2) 2023.11.09
11/08 수업(8일차)  (0) 2023.11.08
11/06 수업 (6일차)  (0) 2023.11.06
11/02 수업 (4일차)  (0) 2023.11.05
11/01 수업 (3일차)  (0) 2023.11.05

** for, 중첩(다중)for

 

* for()

 

* 다중 for문법

 

 

 


** 실습1 **

/* 1
 문제)지난주 마지막 문제를 참고하여 아래와 같이 출력하는 프로그램 작성
 입력예)4
 출력예)[1,1]
     [2,2]
  [3,3]
     [4,4]
 단, 공백은 printf("%5c", ' '); //print("     ")
 */

	      int i, j, num;
	      num = scn.nextInt();	     
	      
	      for(i = 1; i <= num; i++)
	      {
	         for(j = 1; j <= num; j++)
	         {
	            if(i == j)
	            {
                	System.out.printf("[%d,%d]", i, j);
                    //System.out.print("[" + i + "," + j + "]");
	            }
	            else
	            {
                	System.out.print("     ");
	            }
	         }	         
	         System.out.println();
	      }

** 실습2 **

 /* 2
       문제)구구단을 입력 받아 해당 단 일부를 출력하는 프로그램
       단, 입력변수는 a, b를 사용하고 a는 작은단, b는 큰단으로 해서 a부터 b까지 출력.
          출력결과시 (%d * %d = %2d \t)
          입력예)5 2
          출력예)2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10
              ...
              5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25

 */

		int a, b, i, j, tmp;
		
		a = scn.nextInt();
		b = scn.nextInt();
		
		if(a > b)		// a를 작은 값으로 바꾸는 과정
		{
			tmp = a;
			a = b;
			b = tmp;
		}
		for(i = a ; i <= b ; i++ )			//// i - 행 (에서 바뀌지 않는 값)
		{
			for(j = 1 ; j <= 5 ; j++)		// j - 열 (에서 바뀌지 않는 값)
			{
				System.out.printf("%d * %d = %2d \t" ,i ,j, i * j );		// i는 열이고, j는 행이라고 생각하면 좋다.
			}
			System.out.println();
		}

** 반복제어문(소괄호 안에 조건식이 참 일 동안 반복) **

- for / 중첩for / while / do~while / 중첩(다중)while / 무한루프

 

* while 

- 문법

  while(조건식)

  {

      반복 실행문

      증감식;

  }

 

 - 사용법

int a =1;   // while은 초기값을 먼저 세팅해야한다.

whlie(a <= 10)

{

   System.out.println(a);

   a++;

}

 

* do ~while (// 최소 한번은 실행한다.)

 - 문법

   do

   {

          반복 실행문;

          증감식;

    } while(조건식);

 

 

* 무한루프 

 - while(true) / while(1 == 1)

 - for (;;) : 조건식이 존재하지않으면 무한루프

 

 

 

** 이동제어문 ** ( break)

- break / continue / return

 

* break  continue

 - break : 본인을 감싸고있는 가장 가까운 반복문()을 탈출함

 - continue : continue이후에 작성된 코드 실행중단, 반복문 자체를 종료시키지 않는다. ( whlie 조건문으로 for문의 증감식으로 돌아감)

 - Tip : { }안에있는것은 실행이되어야함으로  break와  continue는 { }안에서 맨 마지막에 써야 오류가 뜨지 않는다.

 


* 예제 *

//while(반복문)

 

int a = 0;

while(a <= 10)
{
System.out.println(a);
a++;
//a++없으면 무한으로 실행된다. | a++이 println 앞으로가면 11까지 출력된다.
}

// 위의 whlie문을 for문으로 바꿔보기.
for(a = 1 ; a <= 10 ; a++)
{
System.out.println(a);
}

 


** 실습3 **

/* 3
 문제)알파벳 'A'부터 'Z'까지 출력하는 프로그램 작성
 출력예)ABCDEFGHIJKLNMOPRSTUVWXYZ
 단, 변수는 alpha = 'A' 초기 대입후 사용
 */

		char alpha = 'A';		//char는 ''(작은따옴표)
		
		while(alpha <= 'Z')
		{
			System.out.println(alpha);
			alpha++;
		}

** 실습4 **

/* 4
 문제)1이상 100이하의 정수를 입력받아 whlie문을 이용하여 1부터 입력받은 정수까지의 
  합을 구하여 출력하는 프로그램 작성.
  입력예)10
  출력예)55
 */

		int i, num, sum;
		
		i = 1;
		sum = 0;
		num = scn.nextInt();
		
		while(i <= num)
		{
			sum += i;		//누적변수는 처음에 0으로 설정해야한다.
			i++;
		}
		
		System.out.println(sum);

** 실습5 **

/* 5
 문제)점수를 입력받아 80점 이상이면 합격메세지를 그렇지 않으면 불합격 메세지를 출력하는
  작업을 반복하다가 0~100 이외의 점수가 입력되면 종료하는 프로그램 작성.
  단, while문에 조건식에 비교와 논리연산자 사용. (break 사용안함)
 입출력예)점수를 입력하세요.>50
     죄송합니다. 불합격입니다.
     점수를 입력하세요.>95
     축하합니다. 합격입니다.
     점수를 입력하세요.>101
 */

		int score;
		
		System.out.print("점수를 입력하세요.>");
		score = scn.nextInt();
			
		while(score >= 0 && score <= 100)
		{				
			if(score >= 80)
			{
				System.out.println("축하합니다. 합격입니다.");
			}
			else
			{
				System.out.println("죄송합니다. 불합격입니다.");
			}
			System.out.print("점수를 입력하세요.>");
			score = scn.nextInt();
		}

** 실습6 **

/* 6
 문제)위의 문제를 while 무한루프를 이용하여 작성
 단, while(true) -> break; (continue) -> for(;;)
 */

		int score;
		
		while(true)
		{
			System.out.print("점수를 입력하세요.>");
			score = scn.nextInt();
			
			if (score < 0 || score > 100)
			{
				break;		// break를 감싸고있는 첫번째 반복문(while)을 빠져나간다.
			}
			
			if(score >= 80)
			{
				System.out.println("축하합니다. 합격입니다.");
			}
			else
			{
				System.out.println("죄송합니다. 불합격입니다.");
			}
		}

** 실습7 **

/* 7
 문제)1부터 10까지 반복하면서 홀수만 출력하는 프로그램
  단, continue문 사용
  출력예)1 3 5 7 9
 */

		int num = 0;
		
		while(num < 10)
		{
			num++;
			
			if(num % 2 == 0)
			{
				continue;
			}
			System.out.print(num + " ");
		}
        
        
        // 위와 동일한 조건으로 for문 이용
		int num;
		
		for(num = 1 ; num <= 10 ; num++)
		{
			if(num % 2 == 0)
				continue;
			System.out.print(num + " ");
		}

** 실습8 **

/* 8
 문제)정수를 계속 입력받다가 0이 입력되면 0을 제외하고 이전에 입력된 자료의 수와 합계,
   평균을 출력하는 프로그램
   단, while 무한루프로 사용하고 평균은 소수 둘째자리까지 출력
 입력예)15 88 97 0
 출력예)입력된 자료의 개수는 = 3개
    입력된 자료의 합계 = 200
    입력된 자료의 평균 = 66.67
 */

		int a;
		int sum = 0, count = 0;
		double avg = 0.0;
		
		while(true)
		{
			a = scn.nextInt();
			
			if(a == 0)
				break;			

			sum += a;
			count++;
		}
		
		avg = (double)sum / count;

		System.out.printf("입력된 자료는 개수는 = %d개\n", count);
		System.out.println("입력된 자료의 합계 = " + sum);
		System.out.printf("입력된 자료의 평균 = %.2f \n", avg);
        
        //-----------------------------------------------------------
        
        while(true)
		{
			a = scn.nextInt();
			
			if(a == 0)
				avg = (double)sum / count;
				System.out.printf("입력된 자료는 개수는 = %d개\n", count);
				System.out.println("입력된 자료의 합계 = " + sum);
				System.out.printf("입력된 자료의 평균 = %.2f \n", avg);
				break;			

			count++;
			sum += a;
		}

** 실습9 **

/* 9
 문제)정수를 계속 입력받다가 0 이 입력되면 0을 제외하고 입력된 수 중 홀수의 
  합계와 평균을 출력하는 프로그램
   단, continue와, break문 사용
 입력예)5 8 17 6 31 0
 출력예)홀수의 합 : 53
    홀수의 평균 : 17
 */

		int num;
		int sum = 0, avg = 0, cnt = 0;
		
		while(true)
		{
			num = scn.nextInt();
			if(num == 0)
				break;			
			if(num % 2 == 0)
				continue;
			
			sum += num;
			cnt++;
		}
		
		avg = sum / cnt;
		System.out.println("홀수의 합 : " + sum);
		System.out.println("홀수의 평균 : " + avg);

** do~while문 **

 

* 예제

		//do~whlie 문
        
		int a = 1;
		
		do
		{
			System.out.println(a + "번째 출력");
			a++;
		}while(a <= 10);
        
        //----------------------------------------------------------------------------
        
        		/*
		 문제)위 문제를 while문 무한루프를 사용하여 프로그램작성
		 */
		
		int a = 1;
		
		while(true)
		{
			System.out.println(a + "번째 출력");
			a++;
			
			if(a > 10) break;
		}
        
         //----------------------------------------------------------------------------
		
		// 위 문제를 while문에 조건식을 이용하여 프로그램작성
		
		int a = 1;
		
		while(a <= 10)
		{
			System.out.println(a + "번째 출력.");
			a++;
		}

** 실습10 **

/* 10
 문제)정수를 계속 입력 받다가 0이 입력되면 입력받은 수 중 홀수의 합과 평균을 
   출력하는 프로그램 작성.
   단, do~while문을 사용하고 break, continue는 사용안함.
 입력예)5 8 17 6 31 0
 출력예)홀수의 합 : 53
    홀수의 평균 : 17
 */

		int num, sum = 0, avg, cnt = 0;
		
		num = scn.nextInt();
		do {
			num = scn.nextInt();
			if(num % 2 == 1)
			{
				sum += num;
				cnt++;
			}

		}while(num != 0);
		
		avg = sum / cnt;
		
		System.out.println("홀수의 합 : " + sum);
		System.out.println("홀수의 평균 : " + avg);

** 실습11 **

/*
 문제)아래와 같이 메세지를 출력하고 숫자를 입력받아 선택한 번호에 해당하는 메세지를
   출력하는 작업을 반복하다가 4가 입력되면 메세지 출력 후 종료하는 프로그램
   단, do~while문 사용하고 1~4 이외의 수가 입력되면 "잘못 입력하셨습니다." 라고 출력
 입.출력예)1.입력하기
  2.출력하기
  3.삭제하기
  4.끝내기
  작업할 번호를 선택하세요.>2(4)
 
  출력하기를 선택하셨습니다. (끝내기를 선택하셨습니다.)
 입.출력예)1.입력하기
  2.출력하기
  3.삭제하기
  4.끝내기
  작업할 번호를 선택하세요.>4
 
  잘못 입력되셨습니다. (다시 반복)
 */

		int a;

		do
		{
			System.out.println("1.입력하기");
			System.out.println("2.출력하기");
			System.out.println("3.삭제하기");
			System.out.println("4.끝내기");
			System.out.print("작업할 번호를 선택하세요.>");
			a = scn.nextInt();
			
			System.out.println();
			
			if(a == 1)
			{
				System.out.println("입력하기를 선택하셨습니다.");
			}
			else if(a == 2)
			{
				System.out.println("출력하기를 선택하셨습니다.");
			}
			else if(a == 3)
			{
				System.out.println("삭제하기를 선택하셨습니다.");
			}
			else if (a == 4)
			{
				System.out.println("끝내기를 선택하셨습니다.");	
				break;
			}
			else
			{
				System.out.println("잘못 입력하셨습니다.");
			}
			
		}while(a != 4);

 

		int a;

		do
		{
			System.out.println("1.입력하기");
			System.out.println("2.출력하기");
			System.out.println("3.삭제하기");
			System.out.println("4.끝내기");
			System.out.print("작업할 번호를 선택하세요.>");
			a = scn.nextInt();
			
			System.out.println();
			
			if(a == 1)
			{
				System.out.println("입력하기를 선택하셨습니다.");
			}
			else if(a == 2)
			{
				System.out.println("출력하기를 선택하셨습니다.");
			}
			else if(a == 3)
			{
				System.out.println("삭제하기를 선택하셨습니다.");
			}
			else if (a == 4)
			{
				System.out.println("끝내기를 선택하셨습니다.");	
				break;
			}
			else
			{
				System.out.println("잘못 입력하셨습니다.");
			}
		
			//if를 switch문으로 적용
			
			switch(a) {
			case 1:
				System.out.println("입력하기를 선택하셨습니다.");
				break;
			case 2:
				System.out.println("출력하기를 선택하셨습니다.");
				break;
			case 3:
				System.out.println("삭제하기를 선택하셨습니다.");
				break;
			case 4:
				System.out.println("끝내기를 선택하셨습니다.");	
				break;
			default:
				System.out.println("잘못 입력하셨습니다.");
			}
			
		}while(a != 4);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/08 수업(8일차)  (0) 2023.11.08
11/07 수업 (7일차)  (1) 2023.11.07
11/02 수업 (4일차)  (0) 2023.11.05
11/01 수업 (3일차)  (0) 2023.11.05
10/31 수업 (2일차)  (0) 2023.11.05

** 복습 **

 

변수 설정  :  데이터타입 변수명 = 초기값;

산술연산자중 : / % 용도  
나머지(%)용도 - 1. 짝,홀수 구하기 ex) if(a%2 == 0) 짝수
                                                             if(a%2 != 0) 홀수

                            2. 배수 구하기 ex) if(a%5 == 0) 5의 배수
                                                          if(a%2 != 0) 5의 배수 X


** Scanner ** 정의하기

 

import java.util.Scanner;

public class MySample1102 {

	public static void main(String[] args) 
	{
		Scanner scn = new Scanner(System.in);
	}

}

** 실습1 **

/* 1
 문제)주사위를 두번 던져서 나온 수를 입력받아 두수가 모두 4이상이면 "이겼습니다."
   한개만 4이상이면 "비겼습니다." 모두 4미만이면 "졌습니다."라고 출력하는 프로그램 
   
 입력예)주사위 던진 결과를 입력하세요.>3 4
 출력예)비겼습니다.
 
 입력예)주사위 던진 결과를 입력하세요.>3 8
 출력예)입력값은 1~6사이 값으로 하세요.
 
 단, 주사위 입력값은 1~6사이 값이어야 함. if로만 체크함
 */

import java.util.Scanner;

public class MySample1102 {

	public static void main(String[] args) 
    {
		Scanner scn = new Scanner(System.in);
        
		
		int a = scn.nextInt();
		int b = scn.nextInt();
		
		if (1 <= a && a <= 6 && 1<= b && b <= 6)
		{
			if(a >= 4 && b >= 4)
			{
				System.out.println("이겼습니다.");
			}
			else if(a >= 4 || b >= 4)
			{
				System.out.println("비겼습니다.");
			}
			else
			{
				System.out.println("졌습니다.");
			}			
		}
		else 
		{
			System.out.println("입력값은 1~6사이 값으로 하세요.");
		}     
        
//-----------------------------------------------------------------------------

        //다른 풀이
        
		System.out.print("주사위 던진 결과를 입력하세요.>");		
		int a = scn.nextInt();
		int b = scn.nextInt();
		
		if(a < 1 || a > 6 || b < 1 || b >6)
		{
			System.out.println("입력값은 1~6사이 값으로 하세요.");
		}
		else if(a >=4 && b >= 4)
		{
			System.out.println("이겼습니다.");
		}
		else if(a >= 4 || b >= 4)
		{
			System.out.println("비겼습니다.");
		}
		else
		{
			System.out.println("졌습니다.");
		}
        
	}

}

** 실습2 **

/* 2
 문제)중첩if
   정수 개를 입력받아 그 중 가장 큰 수를 출력하는 프로그램
 입력예)세개의 정수를 입력하세요.>1 5 4
 출력예)입력받은 수 중 가장 큰 수는 5 입니다.
 단, 출력은 max 변수를 사용함
 */

import java.util.Scanner;

public class MySample1102 {

	public static void main(String[] args) 
	{
		Scanner scn = new Scanner(System.in);
		
		System.out.println("세개의 정수를 입력하세요");
		int a = scn.nextInt();
		int b = scn.nextInt();
		int c = scn.nextInt();
		
		if (a >= b) {
			if(a >= c)
			{
				System.out.printf("입력받은 수 중 가장 큰 수는 %d 입니다. \n",a );
			}
			else
			{
				System.out.printf("입력받은 수 중 가장 큰 수는 %d 입니다. \n",c );
			}
		}
		else
		{
			if (b >= c)
			{
				System.out.printf("입력받은 수 중 가장 큰 수는 %d 입니다. \n",b );
			}
			else 
			{
				System.out.printf("입력받은 수 중 가장 큰 수는 %d 입니다. \n",c );
			}
		}

//--------------------------------------------------------------------------------------

		//출력을 max변수로 사용한 경우

		System.out.println("세개의 정수를 입력하세요");
		int a = scn.nextInt();
		int b = scn.nextInt();
		int c = scn.nextInt();
		int max;
		
		if (a >= b) {
			if(a >= c)
			{
				max = a;
			}
			else
			{
				max = c;
			}
		}
		else{
			if (b >= c)
			{
				max = b;
			}
			else 
			{
				max = c;
			}
		}
		
		System.out.printf("입력받은 수 중 가장 큰 수는 %d 입니다. \n", max);
        
        
	}

}
 

Tip - ex) if 절안에서 변수를 선언하면 그 변수를 포함한 if {괄호} 밖에서는 사용할 수 없다.

      - 같은 변수는 한 번 더 선언할 수 없다.


** 실습3 **

/* 3
 문제)점수를 입력받아 90~100점 사이는 'A'이면서 98~100점은 'A+'로 나타내고
   90~93점은 'A-'로 나타내고 94~97점은 'A'로 나타내는 프로그램
 단, 80~83점은 " B-', 84~87점 'B', 88~89점은 'B+'표시로하고 
  A, B를 제외한 나머지는 'c'학접으로 표시함. @점수 입력값은 0~100 이라고 가정한다.
 입력예)점수를 입력하세요.>100
 출력예)당신의 점수는 100점 입니다.
    당신의 학점은 A+입니다.
 
 입력예)점수를 입력하세요.>81
 출력예)당신의 점수는 81점 입니다.
    당신의 학점은 B-입니다.
    
 입력예)점수를 입력하세요.>85
 출력예)당신의 점수는 85점 입니다.
    당신의 학점은 B입니다.
    
 입력예)점수를 입력하세요.>69
 출력예)당신의 점수는 69점 입니다.
    당신의 학점은 C입니다.
 */

import java.util.Scanner;

public class MySample1102 {

	public static void main(String[] args) 
	{
		Scanner scn = new Scanner(System.in);
		
		int score;		//점수
		char grade = ' ', opt = ' ';		//학점, 부호
		
		System.out.println("점수를 입력하세요.>");
		score = scn.nextInt();
		
		System.out.println("당신의 점수는 " + score + "입니다.");
		
		if (score >= 80)
		{
			if(score < 90)
			{
				grade = 'B';
				
				if(score <= 83 )
				{
					opt = '-';
				}
				else if(score <= 87 )
				{
					opt = ' ';
				}
				else
				{
					opt = '+';
				}
			}	
			else
			{
				grade = 'A';
						
				if(score <= 93 )
				{
					opt = '-';
				}
				else if(score <= 97 )
				{
					opt = ' ';
				}
				else
				{
					opt = '+';
				}
			}
		}
		
		else
		{
			grade = 'C';
		}		
		System.out.printf("당신의 학점은 %s%s입니다.",grade, opt);
	
		
	// 다른 풀이
		
		int score;		//점수
		char grade = ' ', opt = ' ';		//학점, 부호
		
		System.out.println("점수를 입력하세요.>");
		score = scn.nextInt();
		
		System.out.println("당신의 점수는 " + score + "입니다.");	
		
		if(score >= 90)
		{
			grade = 'A';
					
			if(score >= 98)
			{
				opt = '+';
			}
			else if(score <= 93)
			{
				opt = '-';
			}
			else
			{
				opt = ' ';
			}
		}
		else if(score >= 80)
		{
			grade = 'B';
			
			if(score >= 88)
			{
				opt = '+';
			}
			else if(score <= 83)
			{
				opt = '-';
			}
			else
			{
				opt = ' ';
			}
		}
		else
		{
			grade = 'C';
			opt = ' ';
		}
		
		
		if(opt == ' ')
		{
			System.out.printf("당신의 학점은 %c입니다. \n", grade);
		}
		else
			{
			System.out.printf("당신의 학점은 %c%c입니다. \n", grade, opt);
            System.out.printf("grade 숫자 %d, 값: %c \n", 
					Integer.valueOf(grade), grade);		//유일하게 char타입은 영문자는 아스키코드와 일치된다.(?)  (Integer.valueOf)
            
	}

}

** 조건문 (switch) **


switch(조건식)      // 조건식을 계산한 값을 분기

{
case 값1:       //값에 변수,실수 불가(문자열 리터럴 가능 JDK1.7부터)
                  //조건식의 결과와 값1이 같은 경우 실행
break;
case 값2:       
                  //조건식의 결과와 값2이 같은 경우 실행
break;
default:
                  //조건식의 결과와 일치하는 경우가 없을 경우 실행
break;
}
 
- break가 없으면 {}끝날때까지 실행
 
Tip - 모든 swich문은 if문으로 표현 간능 (반대는 모두 가능하지는 않음)

 


//** 실습 4 (간단한 예제) <switch~case문>

import java.util.Scanner;

public class MySample1102 {

	public static void main(String[] args) 
	{
		Scanner scn = new Scanner(System.in);

//** switch~case 문

//** 실습 4 (간단한 예제)
			int a =3;
			
			switch(a)
			{
				case 3:
					System.out.println("3 입니다.");
					break;			//break;가 없으면 "default 입니다."까지 출력된다. break는 본인을 감싸고 있는 첫번째 중괄호밖을 빠져나감
				default:
					System.out.println("default 입니다.");
			}

			int a = 2;
			switch(a)
			{
				default:
					System.out.println("default 입니다.");			
				case 3:
					System.out.println("3 입니다.");
//					break;			// "default 입니다." / "3 입니다." 모두 출력됨 default가 마지막에오는경우만 break안써도 된다.
									
			}

//switch~case 문
		
			int a = 5;
			
			switch(3)
			{
				case 1:
					System.out.println("1 입니다.");
					break;
				case 2:
					System.out.println("2 입니다.");
					//break;
				case 3:
					System.out.println("3 입니다.");
					//break;
				default:
					System.out.println("default 입니다.");
			}
            
	}

}

 

** 실습5 **
/* 5
 문제)현재월을 입력받아 계절을 출력하는 프로그램 작성.

 입력예)현재 월을 입력하세요.>11
 출력예)현재 계절은 가을입니다.

 단, 3,4,5 : 봄 . 6,7,8 : 여름 / 9,10,11 : 가을 / 12,1,2, :겨울
   입력값은 1~12사이 (아닐경우 '월을 잘못입력하셨습니다.')
*/

import java.util.Scanner;

public class MySample1102 {

	public static void main(String[] args) 
	{
		Scanner scn = new Scanner(System.in);
		
		System.out.print("현재 월을 입력하세요.>");
		int month = scn.nextInt();
		
			switch(month)
			{
				case 1:
					System.out.println("현재 계절은 겨울입니다.");
					break;
				case 2:
					System.out.println("현재 계절은 겨울입니다.");
					break;
				case 3:
					System.out.println("현재 계절은 봄입니다.");
					break;
				case 4:
					System.out.println("현재 계절은 봄입니다.");
					break;
				case 5:
					System.out.println("현재 계절은 봄입니다.");
					break;
				case 6:
					System.out.println("현재 계절은 여름입니다.");
					break;
				case 7:
					System.out.println("현재 계절은 여름입니다.");
					break;
				case 8:
					System.out.println("현재 계절은 여름입니다.");
					break;
				case 9:
					System.out.println("현재 계절은 가을입니다.");
					break;
				case 10:
					System.out.println("현재 계절은 가을입니다.");
					break;
				case 11:
					System.out.println("현재 계절은 가을입니다.");
					break;
				case 12:
					System.out.println("현재 계절은 겨울입니다.");
					break;
				default:
					System.out.println("월을 잘못입력하셨습니다.");
			}
			
			// 위 문제를 줄이는 방법
			
			System.out.print("현재 월을 입력하세요.>");
			int month = scn.nextInt();
			
				switch(month)
				{
					case 3:
					case 4:
					case 5:
						System.out.println("현재 계절은 봄입니다.");
						break;
					case 6:
					case 7:
					case 8:
						System.out.println("현재 계절은 여름입니다.");
						break;
					case 9:
					case 10:
					case 11:
						System.out.println("현재 계절은 가을입니다.");
						break;
					case 12:
					case 1:
					case 2:
						System.out.println("현재 계절은 겨울입니다.");
						break;					
					default:
						System.out.println("월을 잘못입력하셨습니다.");
				}
				
		
		// 위 문제(switch)를 if문으로 변경
		
		System.out.print("현재 월을 입력하세요.>");
		int month = scn.nextInt();
		
		if(month == 3 || month == 4 || month == 5)
		{
			System.out.println("현재 계절은 봄입니다.");
		}	
		else if(month == 6 || month == 7 || month == 8)
		{
			System.out.println("현재 계절은 여름입니다.");
		}
		else if(month == 9 || month == 10 || month == 11)
		{
			System.out.println("현재 계절은 가을입니다.");
		}
		else if(month == 12 || month == 1 || month == 2)
		{
			System.out.println("현재 계절은 봄입니다.");
		}
		else {
			System.out.println("월을 잘못입력하셨습니다.");
		}
        
	}

}

** 실습6 **

 

/* 6
 문제)아래의 메뉴에서 선택한 메뉴를 알려주는 프로그램.
 단, 해당 숫자 이외에 값을 입력받을 경우 "잘못 입력하셨습니다."라는 메세지 출력
 
 입력예)1.추가
    2.수정
    3.삭제
    메뉴번호를 선택하세요.>2


 출력예)수정을 선택하셨습니다.


 단, switch case문에서는 '추가를', '수정을', '삭제를', '잘못'에 해당하는 문자열
  만 출력하고 최종 한번만 "선택하셨습니다."를 출력하는 프로그램.
 */

		
		System.out.println("1.추가");					//System.out.println("1.추가\r\n" + "2.수정\r\n" + "3.삭제\r\n" + "메뉴번호를 선택하세요.>"); 도 가능
		System.out.println("2.수정");
		System.out.println("3.삭제");
		System.out.print("메뉴번로를 선택하세요.>");
		
		int num = scn.nextInt();
		
		switch(num) {
			case 1:
				System.out.print("추가를");
				break;
			case 2:
				System.out.print("수정을");
				break;
			case 3:
				System.out.print("삭제를");
				break;
			default:			
				System.out.print("잘못");
		}
		
		System.out.println(" 선택하셨습니다.");

** 실습7 **

 

/* 7
 switch문 사용
 문제)점수를 입력받아 학점을 출력하는 프로그램
   점수는 90~100 : 'A', 80~89 : 'B', 70~79 : 'C', 나머지는 'F'로 정의
   (char타입에 memo변수 사용)
   입력예)당신의 점수를 입력하세요.(1~100)>82
   출력예)당신의 학점은 'B'입니다.
 */

import java.util.Scanner;

public class MySample1102 {

	public static void main(String[] args) 
	{
		Scanner scn = new Scanner(System.in);
		
		char memo = ' ';
		int score;
		
		System.out.print("당신의 점수를 입력하세요.>");
		score = scn.nextInt();
		
		switch (score/10) {
			case 10:
			case 9:
				memo = 'A';
				break;
			case 8:
				memo = 'B';
				break;
			case 7:
				memo = 'C';
				break;
			default:
				memo = 'F';
		} 
		
		System.out.printf("당신의 학점은 %s입니다.", memo);
        
	}

}

 


제어문 -> 반복문 중 for

 

** for 문 (for, 다중 for) **

 

* 문법

for(①초기식; ②조건식, 증감식)

{

        ③반복 실행될 문장(실행문);

}

 

// 초기식 - for 문 들어왔을때 한번만 실행

// 조건식 - (T/F) True

// 실행문 - 조건식이 True일 경우에 수행, False 경우 ⑥으로 반복문 빠져나간다.

// 누적되는 변수는 밖에서 초기값 설정 해야한다.

// 초기식,조건식,증감식은 경우에 따라 생략이 가능하지만 ; ; 는 생략 불가

// ① .초기식 → ② . 조건식 (t / f) → ③ .실행문 →   .증감식 → ② .조건식 → ③ .실행문 → .증감식 → ② .조건식(F) → ⑥

 

사용법 예제)

int i, sum = 0;

for(i = 1;i<=5;i++)

{  //1~5까지 합

    sum += i;

    System.out.printf("%d %d", i, sum);

}

 

// printf 결과값 => 5  15

// for문 밖에서 i 값을 출력하면 = 6 이 나온다.


// ** 반복제어문 for문 **

 

// 예제)

		// 예제)
		
		int i, sum = 0;
		
		for(i = 1;i <=5;i++)
		{
			sum += i;			// 의미 => sum = sum + i;
			System.out.println("i=" + i + ", sum" + sum);
		}
		
		System.out.println("for문 끝.");
		System.out.println("i=" + i + ", sum" + sum);

 

결과

i=1, sum1
i=2, sum3
i=3, sum6
i=4, sum10
i=5, sum15
for문 끝.
i=6, sum15

 

 


** 실습8 **

/* 8
 문제)1부터 10까지의 함을 구하고 출력하는 프로그램
 출력예)55
 단, for문으로 적용
 */

		int a, sum = 0;
		
		for (a = 1; a <= 10; a++)
		{
			sum += a  ;
		}
		
		System.out.println(sum);

 

 

 


** 실습9 **

/* 9
 문제)1이상 10이하의 정수를 입력받아 입력받은 정수만큼 반복하며 'JAVA프로그래밍'이라고 출력하는 프로그램
 입력예)3
 출력예)JAVA프로그래밍
 */

		int i = scn.nextInt();
		int j;
		
		for (j = 1;j <= i;j++)			// 초기식에 int j = 1; 로 for문에서 선언을 해도 되지만 그렇게되면 for문 밖에서는 사용 할 수 없다.
		{
			System.out.println("JAVA프로그래밍");
		}

 

 


** 실습10 **

/* 10
 문제)문자를 입력받아서 입력받은 문자를 20번 반복하여 출력하는 프로그램
 단, 입력받을때 char a = scn.nextLine().charAt(0);  // char 문자를 받을 때 맨 앞에 숫자 하나만 받겠다는 의미
 입력예)A
 출력예)AAAAAAAAAAAAAAAAAAAA
 */

		char a = scn.nextLine().charAt(0);
		int i;
		
		for (i=1;i<=20;i++)
		{
			System.out.print(a);
		}

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/07 수업 (7일차)  (1) 2023.11.07
11/06 수업 (6일차)  (0) 2023.11.06
11/01 수업 (3일차)  (0) 2023.11.05
10/31 수업 (2일차)  (0) 2023.11.05
10/30 수업 (1일차)  (0) 2023.11.05

* 아스키코드 
  - ASCII (American Standard Code for Information Interchange) ANSI 미국 표준협회에서 제정한 문자표현방식을 말함
  - 대문자 A 는 65 로 시작해서 1씩증가
  - 소문자 a 는 97로 시작해서 1씩증가

*Tip - 같은 중괄호 안에는 탭을이용해 세로줄 맞추기
        같은 중괄호는 같은 라인에 쓰면 코딩이 길어질때 보기 편하다

 

 

** 제어문 (조건문 / 반복문) **

* 조건문(선택문) (if / switch / case)

· 조건문if 
  -가장 기본 조건문으로 '조건식'과 '괄호{}' 로 이루어

  1. 기본문법 - if (조건식) {
//조건식이 참 일때 수행될 문장들
}


** 실습1 **

/*
 제어문(조건문 - if)
 문제)정수를 입력받아 그 수가 10보다 큰 경우 체크하는 프로그램
 입력예)정수입력>15
 출력예)15
    10보다 큰수를 입력하셨습니다.
    if끝.
    
    9
    if끝.
 */

import java.util.Scanner;

public class MySample1101 
{
	public static void main(String[] args)
	{
		Scanner scn = new Scanner(System.in);
		
		int a;
		
		System.out.print("정수입력>");
		a = scn.nextInt();
		
		if(a > 10)
		{
			System.out.println("10보다 큰수를 입력하셨습니다.");
		}
		
		System.out.println("if끝.");

	}

}

 


** 실습2 **

/*
 문제)if문 2개로 구현
 입력예)숫자를 입력하세요.>3
 출력예)입력하신 숫자는 0이 아닙니다.
    입력하신 숫자는 3입니다.
    
 입력예)숫자를 입력하세요.>0
 출력예)입력하신 숫자는 0입니다.
 */

import java.util.Scanner;

public class MySample1101 
{
	public static void main(String[] args)
	{
		Scanner scn = new Scanner(System.in);
        
		
		int b;
		
		System.out.print("숫자를 입력하세요.>");
		b = scn.nextInt();
		
		if(b != 0)
		{
			System.out.println("입력하신 숫자는 0이 아닙니다.");
			System.out.printf("입력하신 숫자는 %d입니다.", b);
		}
        
		if(b == 0)
		{
			System.out.println("입력하신 숫자는 0입니다.");
		}

	}

}

** 실습3 **

/*
 문제)정수를 입력받아 입력받은 정수ㅡㄹ 출력하고 음수이면 'minus'라고 출력하는 프로그램
 입력예1) -5
 출력예1) -5
   minus
   
 입력예2) 7
 출력예2) 7
 */

import java.util.Scanner;

public class MySample1101 
{
	public static void main(String[] args)
	{
		Scanner scn = new Scanner(System.in);
		
		int c;			// int c= scn.nextInt();		
		c = scn.nextInt();		
		System.out.println(c);
		
		if (c < 0)
		{
			System.out.println("minus");
		}

	}

}

 


실습4

/*
 문제)정수를 하나 입력받아서 0보다 큰 경우, 0인경우, 음수인 경우를 체크하여 출력하는 프로그램.
 단.if문은 3번 사용
 
 입력예1)숫자를 입력하세요.>5
 출력예1)입력하신 값은 5이며, 0보다 큽니다.
 
 입력예2)숫자를 입력하세요.>0
 출력예2)입력하신 값은 0이며, 0과 같습니다..
 
 입력예3)숫자를 입력하세요.>-1
 출력예3)입력하신 값은 5이며, 음수입니다.
 */

import java.util.Scanner;

public class MySample1101 
{
	public static void main(String[] args)
	{
		Scanner scn = new Scanner(System.in);
		
		int a;
		int b = 10;
		
		System.out.print("숫자를 입력하세요.>");
		a = scn.nextInt();
		
		System.out.printf("입력하신 값은 %d이며,",a);
		
		if (a > 0)
		{
			System.out.println("0보다 큽니다.");
		}
		
		///////위와 동일한 것으로 &&, || 테스트용////////
		
		System.out.println("b before : "+ b);
		
		if(a > 0 || ++b > a)	//if(a > 0 && ++b > a)				
		//  &&절에서 &&앞이 false면 &&뒤는 전혀실행하지 않음, 따라서 &&일때 a=0이면 b결과는 10
		//  ||절에서 ||앞이 true면 이미 전체적으로 true이기 때문에 뒤에것은 실행하지않음. 따라서 ||일때 a=1 b결과는 10
		{
			System.out.println("0보다 큽니다.");
		}
		
		System.out.println("b after : " + b);
		
		////////////////////////////////////////
		
		if (a == 0)
		{
			System.out.println("0과 같습니다.");
		}
		if (a < 0)
		{
			System.out.println("음수입니다.");
		}

	}

}

 


실습5

/* 5
 문제)정수 2개를 입력 받아서 큰 수와 작은 수를 차례로 출력하는 프로그램
 입력예)2 9
 출력예)입력받은 수 중 큰 수는 9이고 작은수는 2입니다.
 단, 큰수는 항상 a변수를 사용하고, 작은수는 항상 b변수를 사용하여 출력함.
  변수는 총 세개 a, b, temp 3개를 사용하고 if문 1개 사용.
 */

		
		int a, b, temp;
		
		a = scn.nextInt();
		b = scn.nextInt();

		if(a < b)
		{
			temp =a;
			a = b;
			b = temp;
		}
		
		System.out.printf("입력받은 수 중 큰수는 %d이고, 작은수는 %d입니다.",a , b);

 


** 실습6 **

/* 6
 문제)국어, 영어, 수학, 컴퓨터 총 4과목에 대한 시험점수를 입력 받은 후 평균을 구하고
   각 과목당 점수가 60점 미만이 한과목이 있거나, 평균이 70점 미만이면 불합격 처리하는
   프로그램 작성
   입력예)국어 점수를 입력하세요.>60
      영어 점수를 입력하세요.>70
      수학 점수를 입려하세요.>50
      컴퓨터 점수를 입력하세요.>80
   출력예)불합격 입니다.
   단, 국어 kor, 영어 eng, 수학 math, 컴퓨터 com, 평균 avg 로 함.
    결과 메세지는 String msg로 사용 / 출력은 msg 변수로만 처리함
    if는 한번만 사용함
 */

		int kor, eng, math, com, avg;
		
		System.out.print("국어 점수를 입력하세요");
		kor = scn.nextInt();
		System.out.print("영어 점수를 입력하세요");
		eng = scn.nextInt();
		System.out.print("수학 점수를 입력하세요");
		math = scn.nextInt();
		System.out.print("컴퓨터 점수를 입력하세요");
		com = scn.nextInt();
		
		avg = (kor + eng + math + com) / 4;		
		String msg = "불합격";		// 초기값이 불합격 -> if문 조건 참이면 msg변수가 '합격'덮어진다.		
		
		if(kor >= 60 && eng >= 60 && math >=60 && com >=60 && avg >=70)
		{
			msg = "합격";
		}
		
		System.out.println(msg);

** 실습7 **

/* 7
 if~else 문
 정수를 입력받아 10보다 큰수를 입력받은 경우와 10보다 작은 값을 입력받은 경우를 구분하기 위한 프로그램.
 입력예)15
 출력예)10보다 큰 수를 입력하셨습니다.

 입력예)9
 출력예)10보다 작은 수를 입력하셨습니다.
 */

		int a = scn.nextInt();
		
		if (a > 10)
		{
			System.out.println("10보다 큰 수를 입력하셨습니다.");
		}
		else
		{
			System.out.println("10보다 작은 수를 입력하셨습니다.");
		}

** 실습8 **

/* 8
 문제)점수를 입력받아 80점 이상이면 합격 아니면 불합격을 출력하는 프로그램
 입력예)점수를 입력하세요.>89
 출력예)축하합니다.합격입니다.

 입력예)점수를 입력하세요.>76
 출력예)죄송합니다.불합격입니다.
 */

		int scr;
		System.out.print("점수를 입력하세요.>");
		scr = scn.nextInt();		// int scr = scn.nextInt();  도 가능
		
		if(scr >= 80)
		{
			System.out.println("축하합니다.합격입니다.");
		}
		else
		{
			System.out.println("죄송합니다.불합격입니다.");
		}

** 실습9 **

/* 9
 문제)if~else로 구현
 입력예)숫자를 입력하세요.>3
 출력예)입력하신 숫자는 0이 아닙니다.
    입력하신 숫자는 3입니다.
    
 입력예)숫자를 입력하세요.>
 출력예)입력하신 숫자는 0입니다.
 */

		System.out.print("숫자를 입력하세요.>");
		int a = scn.nextInt();
				
		if (a == 0)
		{
			System.out.printf("입력하신 숫자는 %d입니다. \n", a);
		}		
		else
		{	
			System.out.println("입력하신 숫자는 0이 아닙니다.");
			System.out.printf("입력하신 숫자는 %d입니다. \n", a);
		}
		
		// 위와 조건식이 다른경우
		if (a != 0)
		{
			System.out.println("입력하신 숫자는 0이 아닙니다.");
			System.out.printf("입력하신 숫자는 %d입니다. \n", a);
		}
		else
		{	
			System.out.printf("입력하신 숫자는 %d입니다. \n", a);
			System.out.printf("입력하신 숫자는 %d입니다. \n", a);
		}
		
		// 입력값a가 음수일 경우 문제가 된다.
		if (a > 0)
		{
			System.out.println("입력하신 숫자는 0이 아닙니다.");
			System.out.printf("입력하신 숫자는 %d입니다. \n", a);
		}
		else
		{	
			System.out.printf("입력하신 숫자는 %d입니다. \n", a);
			System.out.printf("입력하신 숫자는 %d입니다. \n", a);
		}

** 실습10 **

/* 10
 문제)if~else if~else
   정수를 입력받아 값이 10보다 큰경우와 0인 경우 음수인 경우를 체크하는 프로그램
 입력예1)정수를 입력하세요.>11
 출력예1)10보다 큰 수를 입력하셨습니다.

 입력예2)정수를 입력하세요.>-1
 출력예2)음수를 입력하셨습니다.

 입력예3)정수를 입력하세요.>10
 출력예3)1에서 10 사이의 정수를 입력하셨습니다.
 */

		System.out.println("정수를 입력하세요.>");
		int a = scn.nextInt();
		
		if(a < 0)
		{
			System.out.println("음수를 입력하셨습니다.");
		}
		else if (0 < a && a < 11)
		{
			System.out.println("1에서 10 사이의 정수를 입력하셨습니다.");
		}
		else
		{
		System.out.println("10보다 큰 수를 입력하셨습니다.");
		}

* Tip - if의 범위를 다룰 때 넓은것부터 좁은것으로 가면 효율적이다.

		// 풀이

		System.out.println("정수를 입력하세요.>");
		int a = scn.nextInt();
		
		if(a > 10)
		{
			System.out.println("10보다 큰 수를 입력하셨습니다.");
		}
		else if (0 > a)
		{
			System.out.println("1에서 10 사이의 정수를 입력하셨습니다.");
		}
		else if (a == 0)
		{	
			System.out.println("0을 입력하셨습니다.");
		}
		else
		{
			System.out.println("음수를 입력하셨습니다.");
		}

** 실습11 **

/*
 문제)점수를 입력받아 '수우미양가'를 출력하는 프로그램
 입력예)점수를 입력하세요.>89
 출력예)우
 단, 90~100:수, 80~89:우, 70~79:미, 60~69:양, 60미만:가
 */

		System.out.println("점수를 입력하세요");
		int score = scn.nextInt();
		
		if(score < 60)
		{
			System.out.println("가");
		}
		else if(score < 70)
		{
			System.out.println("양");
		}
		else if(score < 80)
		{
			System.out.println("미");
		}
		else if(score < 90)
		{
			System.out.println("우");
		}
		else if(score <= 100)
		{
			System.out.println("수");
		}
		
		//첫번째 방법
		if(100 >= score && score >= 90)
		{
			System.out.println("수");
		}
		else if(89 >= score && score >= 80)
		{
			System.out.println("우");
		}
		else if(79 >= score && score >= 70)
		{
			System.out.println("미");
		}
		else if(69 >= score && score >= 60)
		{
			System.out.println("양");
		}
		else if(60 > score)
		{
			System.out.println("가");
		}

//위 문제로 점수는 0~100점 사이만 입력 가능할 수 있도록 처리하는 프로그램
//입력예)점수를 입력하세요.>110
//출력예)점수는 0~100점 사이 입력이 가능합니다.

		System.out.println("점수를 입력하세요");
		int score = scn.nextInt();
		
		if(score < 60)
		{
			if(score < 0)
			{
				System.out.println("점수는 0~100점 사이 입력이 가능합니다.");
			}
			else
				System.out.println("가");
		}
		else if(score < 70)
		{
			System.out.println("양");
		}
		else if(score < 80)
		{
			System.out.println("미");
		}
		else if(score < 90)
		{
			System.out.println("우");
		}
		else if(score <= 100)
		{
			System.out.println("수");
		}
		else if(score > 100)
		{
			System.out.println("점수는 0~100점 사이 입력이 가능합니다.");
		}
		// 다른방법
		
		if(score >= 0 && score <= 100)
		{
			if(score < 60)
			{
					System.out.println("가");
			}
			else if(score < 70)
			{
				System.out.println("양");
			}
			else if(score < 80)
			{
				System.out.println("미");
			}
			else if(score < 90)
			{
				System.out.println("우");
			}
			else if(score <= 100)
			{
				System.out.println("수");
			}	
		}
		else
		{
			System.out.println("점수는 0~100점 사이 입력이 가능합니다.");
		}

** 실습12 **

/* 12
 문제)정수로 월을 입력받아 계절을 출력하는 프로그램.
 입력예)11
 출력예)가을입니다.

 입력예)15
 출력예)잘못입력되었습니다.1~12 사이를 입력하세요.

 단, 봄:3,4,5월 / 여름:6,7,8월 / 가을9,10,11월 / 겨울12,1,2월
  월입력이 1~12사이가 아닌경우 '잘못입력되었습니다.1~12 사이를 입력하세요.'
  비교연산과 논리연산을 활용하여 구현함.
 */

		int month = scn.nextInt();
		
		if (1 <= month && month <=12)
		{
			if(month <= 2 || month == 12 )
			{
				System.out.println("겨울입니다.");
			}
			else if(month >= 9)
			{
				System.out.println("가을입니다.");
			}
			else if(month >= 6)
			{
				System.out.println("여름입니다.");
			}
			else if(month >= 3)
			{
				System.out.println("봄입니다.");
			}
		}
		else
		{
			System.out.println("잘못입력되었습니다.1~12 사이를 입력하세요.");
		}
		// 다른 방법

		if (1 <= month && month <=12)
		{
			if(month == 1 || month == 2 || month == 12 )
			{
				System.out.println("겨울입니다.");
			}
			else if(month == 9 || month == 10 || month == 11)
			{
				System.out.println("가을입니다.");
			}
			else if(month == 6 || month == 7 || month == 8)
			{
				System.out.println("여름입니다.");
			}
			else if(month == 3 || month == 4 || month == 5)
			{
				System.out.println("봄입니다.");
			}
		}
		else
		{
			System.out.println("잘못입력되었습니다.1~12 사이를 입력하세요.");
		}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/07 수업 (7일차)  (1) 2023.11.07
11/06 수업 (6일차)  (0) 2023.11.06
11/02 수업 (4일차)  (0) 2023.11.05
10/31 수업 (2일차)  (0) 2023.11.05
10/30 수업 (1일차)  (0) 2023.11.05

상 수 : 변하지 않는 값 (final를 선언, 리터럴도 포함)

변 수 : 변하는 값 (갑을 저장하는 그릇-데이터를 담아둘 메모리 공간)   //맨 마지막에 담는 것이 남아있음
         변수이름은 알파벳, 숫자, '_', '$' 만 조합 (공백, 특수문자 제외)
         첫글자는 알파벳(대소문자) 또는 '_'와 '$' 시작할 수 있다. (숫자시작은 X)
         대소문자 구분, 예약어 사용 제외 (int, boolean, return, if 등)

자료형 : Data Type  

- 기본자료형 - 문자형 (char<2byte>) (c/c++은 1이지만 자바는 2바이트이기 때문에 자바는 한글로 한글자가 가능하다.)
      - 숫자형 (정수형<byte(1byte), short(1), int(4), long(8)> / 실수형 <float(4), double(8)>)
      - 논리형 (boolean) -> true / false ( 0 / 1 아니다 )
      - 참조자료형 - 클래스 (String, ...)
      - 인터페이스 (Collection, ...)
      - 배열 ( [ ] )

 

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

**실습**

//새클래스 만들기  =  src -> default package -> new -> class -> 이름 MySample1031


//변수

int year = 0; 		// int 자료형 / year 변수명 / = : 초기값세팅 (오른쪽에는 값, 왼쪽에는 값을 담는 변수명)
int age = 15;

System.out.println("year : " + year);
System.out.println("age : " + age);

year = age + 2000; 	// =는 가장 마지막에 계산 / 이번 line 이후로 year은 2015
age = age + 1; 		// 이번 line 밑으로는 age는 16

System.out.println(year);
System.out.println(age);

//------------------------------------------------------------------------------------------------------//

int x, y, z; // 자바에서는 변수선언과 동시에 초기값을 설정해야 사용가능함. -> x,y,z 출력 안됨
int a = 1, b = 2, c = 3;

x = 10;
y = 20;
z = 30;

System.out.println(x);
System.out.println(y);
System.out.println(z);


/*
출력예) x : 10 y : 20
			  x : 20 y : 10
단, x y 변수로만 출력가능   System.out.println("x : " + x + " y : " + y);
			x, y 변수 값으로 교환하여 출력
 */
		
int x = 10, y = 20;
int tmp = 0;		// 변수 두개 값을 바꾸는 방법 -> 임시로 변수만듬  (항상 삼각형을 생각해보기)

System.out.println("x : " + x + " y : " + y);

tmp = x;
x = y;
y = tmp;

System.out.println("x : " + x + " y : " + y);

 

 

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


* Scanner 화면에서 입력받기

  Scanner 클래스를 사용하려면 : import java.util.*;
  Scanner 객체 생성 : Scanner scn = new Scanner(System.in);   -> Scanner (데이터타입이 클래스) / scn (변수명) / new 뒤의 Scanner는 메서드 아니고 생성자

  nextLine() 메서드를 호출하여 입력대기상태에 있다가 엔터키를 누르면 입력내용이 문자열로 반환됨

  String input = scn.nextLine();     -> String (문자형데이터) / input(변수명) / scn안에있는 nextLine메소드를 사용해 input에 담는다.
  int num = Integer.parselnt(input);   -> 입력받은값을 정수형으로 변환

// 두자리 정수를 하나 입력받아 출력하는 프로그램

import java.util.Scanner;

Scanner scn = new Scanner(System.in);
		
System.out.print("정수를 하나 입력하세요.>");
String input = scn.nextLine();			// >뒤에 엔터칠때까지 기다렸다가 치면 문자열로 반환
int num = Integer.parseInt(input);		//Integer.parseInt 문자열을 정수형을로 바꾸는 것

System.out.println("입력바든 값 : " + input);
System.out.printf("num = %d \n", num);


결과 

정수를 하나 입력하세요.>2
입력바든 값 : 2
num = 2

 

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

 

// 상수(final) - 상수는 바꿀수 없다. 상수는 선언과 동시에 초기값 세팅한다. MAX_VALUE 처럼

// 룰 : 변수는 소문자로 시작, 단어와단어 연결할때 두번째 단어부터 첫자대문자로 사용 
          but 상수는 모두 대분자로 쓰되 단어와 단어 사이 언더바를 사용한다.

//상수(final) - 상수는 바꿀수 없다. 상수는 선언과 동시에 초기값 세팅한다. MAX_VALUE 처럼
		
// 룰 : 변수는 소문자로 시작, 단어와단어 연결할때 두번째 단어부터 첫자대문자로 사용 
//		BUT 상수는 모두 대분자로 쓰되 단어와 단어 사이 언더바를 사용한다.
		
final int MAX_SPEED;		//상수 선언시 초기값 설정도 같이하도록함. (1.6이하)
final int MAX_VALUE = 10;	// 상수선언 후 첫번째 값 대입가능 (jdk 1.6 이후부터)
		
MAX_SPEED = 20;
		
System.out.println(MAX_SPEED);
System.out.println(MAX_VALUE);

 

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

 

* 연산자
  특정한 연산을 수행하기 위해 사용하는 기호
  산술, 단항, 비교, 논리, 쉬프트, 기타 연산자로 구분

   ˙ 산술연산자  →  +, -, *, /, %
   ˙ 단항 연산자  →   - (부호연산자)
                          →  ! (논리부정 연산자)
                          →  ++, -- (증감 연산자)
   ˙ 비교 연산자  →  >, <, >=, <=, ==, != (양변을 비교하는 연산)
   ˙ 논리 연산자  →  &&, ||, ^ (AND, OR, XOR 연산)
   ˙ 쉬프트 연산자  → <<, >>, >>> (비트를 이동하는 연산)
   ˙ 기타연산자   → (조건) ? 참 : 거짓 (삼항 연산자)
                          →  =, +=, -=, *= (대입 연산자)


* 연산자 우선순위

* 제어문자 : 문자형에서 특별한 의미를 갖는 문자


** 실습 (산술연산자) **

		//산술연산자
		
		int a = 5;
		int b= a + 2;
		
		a = 7;
		b = 5;
		
		int plus = a + b;
		int minus = a - b;
		int multi = a * b;
		int div = a / b;
		int rest = a % b;
		
		System.out.printf("%d + %d = %d \n", a, b, plus);
		System.out.printf("%d - %d = %d \n", a, b, minus);
		System.out.printf("%d * %d = %d \n", a, b, multi);
		System.out.printf("%d / %d = %d \n", a, b, div);
		System.out.printf("%d %% %d = %d \n", a, b, rest);

 


** 실습 **

		// 증감연산자 (++, --)
		
		// ++a, a++  =>  a + 1     * a 잔신에 1 증가  ++a 전치 : 먼저 증가 후 명령실행 / a++ 후치 : 명령실행 후 다음줄 내려가기 전 증가
		// --a, a--  =>  a - 1     * a 잔신에 1 감소

		a = 5;
		System.out.println("a = " + a);	// 5
		a++;				// 후치증가연산자
		System.out.println("a1 = " + a);	// 6
		++a;				// 전치증가연산자
		System.out.println("a2 = " + a);	// 7

		a = 5;
		System.out.println("a = " + a);	// 5
		System.out.println("a++ = " + a++);	// 5
		System.out.println("++a = " + ++a);	// 7



		// 감소연산자
		
		a = 5;
		System.out.println("a = " +a);
		a--;				// 후치감소연산자
		System.out.println("a1 = " +a);
		--a;				// 전치감소연산자
		System.out.println("a2 = " +a);

		a = 5;
		System.out.println("a = " + a);		// 5
		System.out.println("a = " + a--);	// 5
		System.out.println("a = " + --a);	// 3

** 실습 **

		/*
		 * 출력예) a++ = 10, ++b =11
		 * 실행후 a = 11, b = 10
		 * 		 a-- = 10, --b =11
		 * 실행후 a = 10, b = 10
		 * 단, 최초 값은 a = 10, b = 10로 설정후 적용
		 *
		 */
		
		a = 10;
		b = 10;
		
		System.out.println("a++ = " + a++ + ", ++b = " + ++b);
		System.out.println("실행후 a = " + a + ", b = " + b);
		System.out.println("a-- = " + a-- + ", --b = " + --b);
		System.out.println("실행후 a = " + a + ", b = " + b);

		System.out.printf("a++ = %d, ++b = %d \n", a++, ++b);
		System.out.printf("실행후 a = %d, b = %d \n", a, b);
		System.out.printf("a++ = %d, ++b = %d \n", a--, --b);
		System.out.printf("실행후 a = %d, b = %d \n", a, b);

** 실습 **

		/*
		 * 문제) 정수 변수 첫번째 정수a와 두번째 정수b를 입력받아서 a는 전치증가연산자를 사용하고 b는 후치감소연산자를
		 * 		사용하여 두 수의 합을 c에 저장한 후 각가 출력하는 프로그램 작성
		 * 입력예) 첫번째 정수>5
		 * 		 두번째 정수>6
		 * 출력예) a = 6, b = 5, c = 12
		 * 단, 입력받을때 nextInt() 로 처리하여 정수로 받아 처리함.
		 */
		
		
		int a, b, c;
		
		Scanner scn = new Scanner(System.in);		// 키보드로 입력받을땐 무조건이렇게 쓴다고 일단 외우기
		
		System.out.print("첫번째 정수>");
		a = scn.nextInt();
		System.out.print("두번째 정수>");
		b = scn.nextInt();
		
		c = ++a + b--;
		
		System.out.printf("a = %d,b = %d, c = %d \n", a, b, c);

 

** 실습 (비교연산자) **

		// 비교연산자 => 결과가 true / false 중 하나
		
		int a = 10;
		int b = 20;
		int c =20;
		
		System.out.println("a == b : " + (a == b));		//false
		System.out.println("b == c : " + (b == c));		//true
		System.out.println("a != b : " + (a != b));		//true
		System.out.println("b != c : " + (b != c));		//false
		System.out.println("a > b : " + (a > b));		//false
		System.out.println("b >= a : " + (b >= a));		//true
		System.out.println("a <= c : " + (a <= c));		//true
		System.out.println("b < c : " + (b < c));		//false

** 실습 **

		/*
		 * 문제) 3개의 정수를 각각 a,b,c 변수에 입력을 받아 a와 b, b와 c를 각각 비료하여 같으면 true, 같지 않으면 false 출력하는 프로그램
		 * 입력예)a값을 입력하세요.>10
		 * 		b값을 입력하세요.>20
		 * 		c갑을 입력하세요.>2-
		 *
		 * 출력예)a == b : false
		 * 		b == c : true
		 * 		a != b : true
		 * 		b != c : false
		 */
		
		int a, b, c;
		
		Scanner scn = new Scanner(System.in);
		
		System.out.print("a값을 입력하세요.>");
		a = scn.nextInt();
		System.out.print("b값을 입력하세요.>");
		b = scn.nextInt();
		System.out.print("c값을 입력하세요.>");
		c = scn.nextInt();
		
		System.out.println("a == b : " + (a == b));
		System.out.println("b == c : " + (b == c));
		System.out.println("a != b : " + (a != b));
		System.out.println("b != c : " + (b != c));

** 실습 **

 

* 논리 연산자 (&&, ||)  => 왼쪽과 오른쪽의 결과가 true/false 나옴 (&&는 양쪽모두 true일때 true)(||는 둘중하나가 true이면 true)

		int a =1;
		int b =2;
		int c = 3;
		
		System.out.println("(a > b && b < c) : " + (a > b && b < c));
		System.out.println("(a > b && b < c) : " + (a > b || b < c));

** 실습 **

		/*
		 * 문제) 3개의 정수를 각각 a, b, c 를 선언하고 각각 10, 20, 30 으로 초기화 한후
		 * 		비교연산과 논리연산자를 이용하여 참이면 true, 거짓이면 false를 출력하는 프로그램
		 * 출력예) a > b && a<=b : false
		 * 		a > b || a <= b : true
		 * 		b < c && a < c : true
		 * 		!(a > b && a <= b) : true
		 */
		
		int a = 10;
		int b = 20;
		int c = 30;
		
		System.out.println("a > b && a<=b : " + (a > b && a<=b));
		System.out.println("a > b || a <= b : " + (a > b || a <= b));
		System.out.println("b < c && a < c : " + (b < c && a < c));
		System.out.println("!(a > b && a <= b) : " + (!(a > b && a <= b)));

** 실습 (삼항연산자) **

 

* 삼항 연산자 (항이 세개) 앞의 조건이 참이면 콜론전 실행 , false면 콜론 후 실행

		int x = 10, y = 5;
		int result = (x >= y) ? x : y;
		
		System.out.println("x와 y값 중 큰값은 " + result + "입니다.");

** 실습 **

		/*
		 * 문제) 정수변수 a에 나이를 입력받아 19 보다 큰 값을 입력 받았으면 '성인입니다.'로 출력하고
		 * 		19보다 자그면 '청소년입니다.; 라고 출력하는  프로그램.
		 * 입력예) 나이를 입력하세요.>15
		 * 출력예) 청소년입니다.
		 * 단, 삼항연산자를 이용하여 출력에 사용할 변수는 String memo로 정의함.
		 * 	예. String memo = "";
		 * 		memo = "청소년입니다."
		 */
		
		int a;
		
		Scanner scn = new Scanner(System.in);
		
		System.out.print("나이를 입력하세요.>");
		a = scn.nextInt();
		
		String memo = "";			// memo 선언
		memo = (a < 19) ? "청소년입니다." : "성인입니다.";    // String memo = = (a < 19) ? "청소년입니다." : "성인입니다.";  <선언과 동시에 값입력>
		
		System.out.println(memo);

** 실습 **

/*
 문제) 시험점수 3과목을 입력받아 평균을 구한후 통과유무를 출력하는 프로그램작성.
    평균점수가 70점 이상이면 통과, 미만이면 미통과로 처리하는 프로그램.
 입력예)국어 점수를 입력하세요.>80
    영어 점수를 입력사세요.>70
    수학점수를 입력하세요.>90
 출력예)당신의 평균은 80점이고 통과하셨습니다. (70점 이상인 경우)

    당신의 평균은 65점이고 미통과하셨습니다. (70점 미만인 경우)
 단, 국어 kor / 영어 eng / 수학 math / 평균 avg / 통과여부 memo
  String 타입의 printf 서식문자는 %s
  평균 : (국어+영어+수학)/3     
 */

		int kor, eng, math, avg;
		
		Scanner scn = new Scanner(System.in);
		System.out.print("국어 점수를 입력하세요.");
		kor = scn.nextInt();
		System.out.print("영어 점수를 입력하세요.");
		eng = scn.nextInt();
		System.out.print("수학 점수를 입력하세요.");
		math = scn.nextInt();
		
		avg = (kor+eng+math)/3;		
		
		String memo = (avg>=70) ? "통과하셨습니다." : "미통과하셨습니다.";
		
		System.out.printf("당신은 평균은 %d점이고 %s", avg, memo);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/07 수업 (7일차)  (1) 2023.11.07
11/06 수업 (6일차)  (0) 2023.11.06
11/02 수업 (4일차)  (0) 2023.11.05
11/01 수업 (3일차)  (0) 2023.11.05
10/30 수업 (1일차)  (0) 2023.11.05

컴파일러 - 프로그래밍 언어(고급언어)를 컴퓨터가 알아들을수 있는 언어(기계어)로 변환해 주는 것
-> 내가 사용하는것은 openjdk

os(window)에 openjdk(컴파일러)

* eclipse 환경변수 ->  window  어디를가든 openjdk를 사용할 수 있도록 설정했음
* eclipse 툴 다운로드 -> 윈도우에 preference 에 java(jdk를 통해)를 쓸수 있도록 설정


c, c++, java           ->  컴파일러 있어야 실행가능 (컴파일러 언어)
python, JavaScript   -> 컴파일러 없어도됨 (인터프리터 언어)



* 컴파일러 언어
  컴파일러를 통해 전체 소스코드를 한번에 기계어로 변환 후 실행파일 생성
  컴파일 단계과 실행 단계가 각각 분리되어있음
  컴파일은 한번만 수행
  컴파일/실행단계 분리로 실행시에는 실행만 하면되므로 코드실행속도가 빠름

* 인터프리터 언어
  프로그랭밍 언어의 소스코드를 바로 실행하는 프로그램
  코드 한 줄 씩 중간 코드인 바이트코드로 변환 후 실행
  실행파일 생성없음
  한줄씩 바이트코드로 변활 후 즉시 실행
  컴파일/실행단계분리되어있지 않아 반복수행함으로 실행속도가 느림



* java특징 - 운영체제(윈도우,리눅스,유닉스,,,)의 독립적(이식성이 높다)
                ->JAVA는 JVM(java virtual machine) 위에서 돌아가기 때문 (다른언어는 운영체제이서 돌아감)
             - 객체지향언어 (상속, 캡슐화, 다형성)
             - C++에서 연산자.기본구분 + 스몰톡에서 객체지향언어관련 구문 가져옴
             - Garbage Collection(자동메모리관리)
               -> 자동적으로 메모리 관리를 해줌 : 따로 관리 불필요
             - 네트워크와 분산처리지원
             - 멀티쓰레드 지원


* Java SE (Standard Addition)

  -JDK(java development Kit) : 자바 개발 키트
  -JRE(Java Runtime Environment) : 자바 실행 환경
  -JVM(Java Virtual Machine) -> JRE에 포함되어 있음
    자바를 실행하기 위한 가상 머신
    자바로 작성된 애플리케이션은 모두 이 가상컴퓨터(JVM)에서만 실행되기 때문에 자바에플리케이션이 실행되기 위해서는 반드시 JVM 필요


 

- bit 1 자리 (0 또는 1)
- byte = bit 8개  (JAVA는 byte로 컴파일됨)
  ex) 1byte -> 00101000

- 대문자로시작 .java -> 클래스
- 소문자로시작        -> 메소드 ( ex>main )
  => 의무는 아니지만 대체로 이렇게 함

- 소괄호 앞의 단어는 무조건 메소드
- 소괄호 안에는 매개변수 (있을때도 없을때도 있음)
- class 의 시작과 끝은 중괄호 열고 닫는다.


* java 언어 프로그램 기본 구조

 

** Hello.java 작성 ----(javac.exe)(컴파일)----> Hello.class 생성 ----(java.exe)(실행)----> "Hello World" 출력

  class 클래스이름{
	public static void main(String[]args){	// main메소드 선언부		
		// 실행될 문장들을 적는다.
	}
}
public class Hello {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*첫번째 실습
		 * System.out.println("Hello, World...");
		System.out.println("1111111");
	}
}

 


 

- 모든 자바프로그램에서  뭔가 가져다 쓰려면 정의를 해줘야함
- 하지만 Java.랭.object 에서 가져다 쓴다.(jdk)
- System.out.println() -> println은 메소드
- 어떤 이름뒤에 소괄호 ()있으면 그 앞에있는 단어는 무조건 메소드

- public이 붙은 class 뒤의 이름은 파일 명과 같아야한다 (public 없으면 상관없음)
- public class는 둘 이상 안됨


 

* 주석문(comment) - 프로그램 설명을 기입하는 것으로 컴파일과 실행을 하지 않음.(설명)

// : 한줄주석(뒤부터 한줄만 주석)
/* */ : 범위주석. 한줄 혹은 여러줄 주석(/*로 시작해서 */끝날때까지 주석)
Ex) /************************************
   여기주석
************************************/


 

* 대문자로시작 .java -> 클래스
 소문자로시작        -> 메소드 ( ex>main )
=> 의무는 아니지만 대체로 이렇게 함



* 표준 입출력 클래스(출력)
  - 자바에서는 System이라는 표준 입출력 클래스를 정의하여 제공
  - 이러한 System클래스는 java.lang 해키지에 포함되어 제공
 
  - System.in 스트림을 사용하여 표준 입력 작업

  - System.out.println()
  - System.out.println(출력할데이터)

   println 은 줄바꿈 (출력후 엔터 적용)
   print 줄바꿈없음


 

 **실습** (항상 왼->오/위->아래 방향)

public class Hello {

	public static void main(String[] args) {
		System.out.print(7);		//print() 메소드는 줄 바꿈을 하지 않는다.
		System.out.println(3);
		System.out.println(3.14);	//실수 출력
		System.out.println("자바!!");		//문자열 출력
		System.out.println("문자열끼리의 " + "연결도 가능합니다.");
		System.out.println("숫자" + 3 + 7 + "과 문자열의 연결도 가능합니다.");
		System.out.println(3 + 7 + "이번 결과는...");
	}
}

/*
실행 결과=>
73
3.14
자바!!
문자열끼리의 연결도 가능합니다.
숫자37과 문자열의 연결도 가능합니다.
10이번 결과는...
*/

 


 

* printf 출력 서식


%d 정수
%f 실수
%c 문자(' ')     -> 한글자
%s 문자열(" ")  -> 한글자 이상
%o
%x
%b
%B
%e


cf) \n -> 줄바꿈
    System.out.println();  -> 줄바꿈
   
    Ctrl + s   -> 저장
    Ctrl + F11   ->  실행 (run)


 

** 실습 **

		// printf 서식문자 (%d, %f, %c, %s)
		System.out.printf("정수 첫번째 %d, 정수 두번째 %d 입니다.\n", 10, 20);
		System.out.printf("실수 %f 입니다.\n", 2.6123456);
		// 실수를 소수점 둘째자리까지만 출력 (반올림)
		System.out.printf("소수점 둘째자리 실수 %.2f 입니다.\n", 26.123456);
		System.out.println();
		System.out.printf("문자 %c 입니다.\n", 'A');	// "A" 하면 오류남
		System.out.printf("문자 %c 입니다.\n", '가');	// 자바는 된다 (한글도 한글자로 인식)
		System.out.printf("문자열 %s 입니다.\n", "테스트");


		결과
		정수 첫번째 10, 정수 두번째 20 입니다.
		실수 2.612346 입니다.
		소수점 둘째자리 실수 26.12 입니다.

		문자 A 입니다.
		문자 가 입니다.
		문자열 테스트 입니다.

 


 

** 실습 **

		/* 출력예) 수식을 출력하면 계산 결과 출력됩니다.
		 * 		10 + 5 = 15
		 * 		내 생일은 2005년 5월 8일 입니다.
		 * 		
		 * 		단) printf 메서드를 사용.
		 * 		   2번째줄 출력은 -> 10, 5, 10 + 5
		 * 		   3번째줄 출력은 -> 2016-11, 5, 8
		 */

		System.out.printf("수식을 출력하면 계산 결과 출력됩니다.\n");
		System.out.printf("%d + %d = %d\n", 10, 5, 10+5);
		System.out.printf("내 생일은 %d년 %d월 %d일 입니다.\n", 2016-11, 5, 8);

		System.out.print("수식을 출력하면 계산결과 출력됩니다.\n");
		System.out.printf("%s \n", "수식을 출력하면 계산결과 출력됩니다.");
		System.out.printf("%d + %d = %d\n", 10, 5, 10+5);
		System.out.printf("내 생일은 %d년 %d월 %d일 입니다.\n", 2016-11, 5, 8);

 


 

** 실습 **

// 정렬 (왼쪽 / 오른쪽)

		System.out.printf("숫자가 [%8d]입니다.\n", 123);		// 숫자는 기본으로 오른쪽 정렬 | %8d 숫자앞에 8자리 공간을 확보한다는 의미
		System.out.printf("숫자가 [%-8d]입니다.\n", 123);		// 숫자 왼쪽정렬하기
		System.out.printf("알파벳 [%10s]입니다.\n", "abc");
		System.out.printf("알파벳 [%-10s]입니다.\n", "abc");

//=> 결과
	숫자가 [     123]입니다.
	숫자가 [123     ]입니다.
	알파벳 [       abc]입니다.
	알파벳 [abc       ]입니다.

 


 

** 실습 **

		/* 출력예)  subject      score      (subject 8개 공백5  score 6개)
				 ===================
				    korea         90
				  english        100
				 conputer         80
			단) printf 메서드를 이용하여 ""에는 서식문자와 줄바꿈만 표함
			   subject는 문자 3자리(%8s), score 숫자6자리(%6d)로 고정
			   		*/
		
		System.out.printf("%8s%5s%6s\n", "subject"," ", "score");
		System.out.printf("%s\n", "===================");
		System.out.printf("%8s%5s%6d\n", "korea"," ", 90);
		System.out.printf("%8s%5s%6d\n", "english"," ", 100);
		System.out.printf("%8s%5s%6d\n", "computer"," ", 80);
		System.out.printf("%8s     %6s \n", "subject", "score");



// 결과

 subject      score
===================
   korea         90
 english        100
computer         80
 subject      score

 

 

 

 

 

 

 

 

'수업끄적끄적_7MONTH > Java' 카테고리의 다른 글

11/07 수업 (7일차)  (1) 2023.11.07
11/06 수업 (6일차)  (0) 2023.11.06
11/02 수업 (4일차)  (0) 2023.11.05
11/01 수업 (3일차)  (0) 2023.11.05
10/31 수업 (2일차)  (0) 2023.11.05

+ Recent posts