1. Collection의 개념을 이해하고 기술할 수 있다. (자바의 데이터 자료관리를 구현할 수 있다.)

    list : 자료의 데이터를 인덱스로 관리한다. 중복 데이터 가능, null 가능

      - ArrayList, Vector
    set : 값으로 데이터를 관리한다. 중복 데이터 허용 불가능, null 하나만 가능

      - HashSet
    map : 키와 값으로 데이터가 저장되고 키로 데이터를 관리한다. 중복 데이터 가능, null 가능, 키 중복 불가능

      - HashMap
 
하는 이유?
  1. 원하는 타입을 
  2. 동적으로 관리할 수 있다.

 

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

1. List

package com.Collections;

import java.util.*;
import com.exam.Score;

public class Test {
	public static void Prn01() {
		List<Score> li = new ArrayList<Score>();

		li.add(new Score("홍길동", 90, 70, 60));
		li.add(new Score("홍길동1", 90, 70, 60));
		li.add(new Score("홍길동2", 90, 70, 60));
		li.add(new Score("홍길동3", 90, 70, 60));

		list_print(li);

		List<Score> rm = list_print02(li); // list_print02() 메서드를 통해서 값 변경 후 리턴 받는다.
		list_print(rm);

	}

	public static void list_print(List<Score> listall) {
		for (Score res : listall) {
			System.out.println(res);
		}
	}

	public static List<Score> list_print02(List<Score> all) {
		// 국어 점수를 모두 100점으로 변경하자
		for (Score s : all) {
			s.setKor(100);
		}

		return all;
	}
	
	public static void list_print03(List<Score> all) {
		System.out.println("============================");
		Iterator<Score> ir = all.iterator(); // Iterator -> next() haNext()
		
		while(ir.hasNext()) {
			System.out.println(ir.next());
		}
	}

	public static void main(String[] args) {
		Prn01();
	}

}

 

2. Set

package com.Collections;
import java.util.*;
import com.exam.*;

public class Test02 {
	public static void Prn() {
		Set<Score> si = new HashSet<Score>();
		
		si.add(new Score("홍길동", 90, 70, 60));
		si.add(new Score("홍길동1", 90, 70, 60));
		si.add(new Score("홍길동2", 90, 70, 60));
		
		Score score = new Score("홍길동3", 90, 70, 60);
		si.add(score);
		
		si.add(score);
		si.add(score);
		
		for (Score sm : si) {
			System.out.println(sm);
		}
	}
	
	public static void Prn02() {
		Set<String> si02 = new HashSet<>();
		si02.add("abc");
		si02.add("abc");

		si02.add(new String("abcd"));
		si02.add(new String("abcd"));
		
		for (String sm : si02) {
			System.out.println(sm);
		}
	}

	public static void main(String[] args) {
		Prn();
		Prn02();
	}

}

 

3. Map

package com.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.exam.Score;

public class Test03 {
	public static void Prn() {
		Map<Integer, String> m1 = new HashMap<>();
		m1.put(11, "1임");
		m1.put(22, "2임");
		m1.put(33, "3임");
		
		System.out.println(m1);
		System.out.println(m1.keySet());
		System.out.println(m1.values());

		m1.put(1, "1");
		System.out.println(m1);
		
		Set<Entry<Integer, String>> res = m1.entrySet();
		System.out.println(res);
	}
	
	public static void Prn02() {
		Map<Integer, Score> si = new HashMap<>();
		
		si.put(1, new Score("홍길동", 90, 70, 60));
		si.put(2, new Score("홍길동1", 90, 70, 60));
		si.put(3, new Score("홍길동2", 90, 70, 60));
		
		System.out.println(((Object)si).getClass());
		System.out.println(si);
		System.out.println(si.values());
		System.out.println(si.keySet());
		
		Set<Map.Entry<Integer, Score>> res = si.entrySet();
		System.out.println();
		System.out.println(res);
		
		for(Map.Entry<Integer, Score> i : res ) {
			System.out.println("Key : " + i.getKey() + ",\tValue : " + i.getValue());
		}
	}

	public static void main(String[] args) {
		Prn02();
		
		
	}

}

1. GUI를 연동할 수 있다. <이벤트>
javaFX는 자바스크립트 연동을 위해?

BorderLayout : 디폴트 레이아웃. 크기 조절은 안됨
BoxLayout, CardLayout, FlowLayout, GridLayout 등

끝자리가 Listener면 전부 이벤트
끝자리가 Adapter면  이벤트를 다 오버라이드 할 필요 없다.

프레임은 생략하고 이벤트 위주로 설명

 

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

1. 인터페이스를 implements 하는 이벤트 적용 방법

package com.GUI_Event;

import java.awt.Button;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

// case 1 : 인터페이스를 implements 하는 이벤트 적용 방법
public class MyFrame extends Frame implements WindowListener {
	Panel p1;
	Button bt;

	public MyFrame() {
		super("내꺼");
		p1 = new Panel();
		bt = new Button("!!!!");
	}

	public void go() {

		// 레이아웃
		setFont(new Font("Serif", 3, 30));
		p1.add(bt);
		add(p1);

		// 이벤트 구현
		// 1. 대상의 addXXXListener() 를 기능에 따라 찾는다
		addWindowListener(this);

		// 2. ()의 매개인자를 통해서 해당 이벤트에 맞는 메소드가 있는지 찾는다. => 구현한다.

		// 프레임 실행 시점
		setSize(400, 400);
		setVisible(true);
	}

	public static void main(String[] args) {
		new MyFrame().go();
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowClosing(WindowEvent e) {
		System.out.println("windowClosing");
		System.exit(0);
	}

	@Override
	public void windowClosed(WindowEvent e) {
		System.out.println("windowClosed");
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub

	}

}

 

2. WindowListener 인터페이스를 익명으로 implements 하는 이벤트 적용 방법

package com.GUI_Event;

import java.awt.Button;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

// case 2 : WindowListener 인터페이스를 익명으로 implements 하는 이벤트 적용 방법
public class MyFrame02 extends Frame {
	Panel p1;
	Button bt;

	public MyFrame02() {
		super("내꺼");
		p1 = new Panel();
		bt = new Button("!!!!");
	}

	public void go() {

		// 레이아웃
		setFont(new Font("Serif", 3, 30));
		p1.add(bt);
		add(p1);

		// 이벤트 구현
		// 1. 대상의 addXXXListener() 를 기능에 따라 찾는다
		addWindowListener(new WindowListener() {

			@Override
			public void windowOpened(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowIconified(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowDeiconified(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowDeactivated(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}

			@Override
			public void windowClosed(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowActivated(WindowEvent e) {
				// TODO Auto-generated method stub

			}
		});

		// 2. ()의 매개인자를 통해서 해당 이벤트에 맞는 메소드가 있는지 찾는다. => 구현한다.

		// 프레임 실행 시점
		setSize(400, 400);
		setVisible(true);
	}

	public static void main(String[] args) {
		new MyFrame02().go();
	}

}

 

3. 추상클래스 익명으로 정의하는 방법

package com.GUI_Event;

import java.awt.Button;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// case 3 : 추상클래스 익명으로 정의하는 방법
public class MyFrame03 extends Frame {
	Panel p1;
	Button bt;

	public MyFrame03() {
		super("내꺼");
		p1 = new Panel();
		bt = new Button("!!!!");
	}

	public void go() {

		// 레이아웃
		setFont(new Font("Serif", 3, 30));
		p1.add(bt);
		add(p1);

		// 이벤트 구현
		// 1. 대상의 addXXXListener() 를 기능에 따라 찾는다
		addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
			
		});

		// 2. ()의 매개인자를 통해서 해당 이벤트에 맞는 메소드가 있는지 찾는다. => 구현한다.

		// 프레임 실행 시점
		setSize(400, 400);
		setVisible(true);
	}

	public static void main(String[] args) {
		new MyFrame03().go();
	}

}

 

4. 이너클래스로 처리할 수 있다.

package com.GUI_Event;

import java.awt.Button;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// case 4 : 이너클래스로 처리할 수 있다.
public class MyFrame04 extends Frame {
	Panel p1;
	Button bt;

	public MyFrame04() {
		super("내꺼");
		p1 = new Panel();
		bt = new Button("!!!!");
	}

	public void go() {

		// 레이아웃
		setFont(new Font("Serif", 3, 30));
		p1.add(bt);
		add(p1);

		// 이벤트 구현
		// 1. 대상의 addXXXListener() 를 기능에 따라 찾는다
		addWindowListener(new MyEvent());
		bt.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.out.println("버튼을 클릭했어!!!!!!!!");
				
			}
		});

		// 2. ()의 매개인자를 통해서 해당 이벤트에 맞는 메소드가 있는지 찾는다. => 구현한다.

		// 프레임 실행 시점
		setSize(400, 400);
		setVisible(true);
	}

	class MyEvent extends WindowAdapter {

		@Override
		public void windowClosing(WindowEvent e) {
			System.exit(0);
		}

	}

	public static void main(String[] args) {
		new MyFrame04().go();
	}

}

자바의 파일입출력
1. java.io : 기본 탐색기에서 이루어지는 모든 기능을 클래스로 만들어 놓은 패키지.
       1bit(0,1) * 8 = 8bit = 1byte
             byte 단위 (1byte) 입출력 : 이미지, 영상, 소리 등의 파일을 입출력할 때 사용     일단은 얘가 기준임
             char 문자단위 (2byte) 입출력 : 한문자 단위 및 char[] <=> String         네트워크 전송할 때 이건 잘 안씀
             객체 단위 입출력 : .class 단위로 입출력할 때 사용
             
             파일과 디렉토리를 관리하는 클래스 : File
             
             File의 CRUD 찾아놓을 것 
             C : createTempFile(String prefix, String suffix),  createTempFile(String prefix, String suffix, File directory)
             R : list(), listFiles()
             U : renameTo(파일명이 같은 애의 경로를 옮김)
             D : delete()

 

2. java.nio가 있지만 배우지는 않았다.

 

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

1. File 클래스가 가진 생성자와 메소드

package com.FileIO;

import java.io.File;

// File 클래스가 가진 생성자와 메소드를 살펴보자.
public class Test01 {
	
	// File(String pathname);
	public static void prn01() {
		File f = new File("c:\\Utest");
		if (f.exists()) {
			System.out.println("이미 경로가 존재함");
		} else {
			f.mkdir();
			System.out.println("지금 만들었음");
		}
	}
	
	// File(String parent, String child);
	public static void prn02() {
		File f = new File("c:\\UTest", "MyTest");
		f.mkdir();
	}
	
	// File(File parent, String child);
	public static void prn03() {
		File parent = new File("c:\\UTest");
		File f = new File(parent, "MyTest02");
		f.mkdir();
	}

	public static void main(String[] args) {
		prn01();
		prn02();
		prn03();
        
		System.out.println(File.pathSeparator );
		System.out.println(File.pathSeparatorChar );
		System.out.println(File.separator );
		System.out.println(File.separatorChar );
		
		String path = "c:" + File.separatorChar + "UTest" + File.separator + "YTest";
		System.out.println(path);
		File fi = new File(path);
		fi.mkdir();
		
	}

}

 

2. 파일위치 변경, 파일/디렉토리 확인

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

public class Test02 {
	public static void disp() {
		File f = new File("c:\\Utest");
		File fi = new File(f, "a.txt");
//		System.out.println(fi);
		try {
			fi.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// 같은 폴더에 renameTo 해볼 것
	public static void disp02() {
		// 1. Utest 디렉토리에 있는 a.txt를 c:\\test로 이동
		File fi = new File("C:\\Utest\\a.txt");
		fi.renameTo(new File("C:\\Utest\\MyTest\\a.txt"));
	}

	// 지정된 디렉토리의 파일의 개수와 디렉토리 개수를 출력해보자
	public static void disp03() {
		int file_cnt = 0;
		int dir_cnt = 0;

		String path = "C:\\Windows\\System32";
		File file = new File(path);

		// 전체 목록을 File 객체의 배열로 리턴
		File[] file_list = file.listFiles();

		// isXX 메소드를 통해 파일과 디렉토리를 판별
		// 조건에 따라 개수를 계산
		for (File r : file_list) {
			if (r.isFile()) {
				file_cnt++;
				System.out.println("dir : " + r.getName());
			}
			if (r.isDirectory()) {
				dir_cnt++;
				System.out.println("file : " + r.getName());
			}
		}
		System.out.println("전체 개수 : " + file_list.length);
		System.out.println("파일 개수 : " + file_cnt);
		System.out.println("디렉토리 개수 : " + dir_cnt);

	}

	public static void main(String[] args) {
		disp();
		disp02();
		disp03();

	}

}

 

3. 문자단위 파일 입출력

// 1. 문자 단위로 파일 입출력을 하자
public class Test03 {
	public static void MyWrite(File f) throws IOException {
		// false가 default, true를 주면 덮어쓰기 아니고 이어쓰기 됨
		FileWriter fw = new FileWriter(f, true);
		fw.write("ABCDEFG\n");
		fw.append("111111111111\n");
		fw.write("asdfa4asdfasdfasdf\n");

		char[] res = "a95y중간에 한글 되는가d".toCharArray();
		fw.write(res);

		fw.close();
	}

	public static void MyRead(File f) throws IOException {
		FileReader fr = new FileReader(f);
		int ch = 0;

		// 파일의 끝이 -1이 될 때까지 글자를 하나씩 읽어서 ch로 리턴받아 출력하자
		while ((ch = fr.read()) != -1) {
			System.out.printf("%c", (char) ch);
		}

		fr.close();
	}

	public static void main(String[] args) {
		String filename = "Test03.txt";
		File f = new File(filename);
		try {
			MyWrite(f);
			MyRead(f);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

4. byte단위 파일입출력

package com.FileIO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

// 2. byte 단위로 파일 입출력을 하자 원래목적은 이미지 영상 소리용임
public class Test04 {
	public static void MyWrite(File f) throws IOException {
		FileOutputStream fos = new FileOutputStream(f);

		for (int i = 65; i < 91; i++) {
			fos.write(i);
		}
		
		String msg = "오늘은 수요일입니다. 배고픕니다.";
		
		fos.write(msg.getBytes());
		fos.close();
	}

	public static void MyRead(File f) throws IOException {
		FileInputStream fis = new FileInputStream(f);
		int ch = 0;

		while ((ch = fis.read()) != -1) {
			System.out.print((char)ch);
		}
		fis.close();

	}

	public static void main(String[] args) {
		File fi = new File("Test04.txt");

		try {
			MyWrite(fi);
			MyRead(fi);
		} catch (IOException e) {
			System.out.println(e);
			e.printStackTrace();
		}
	}

}

 

5. byte단위로 버퍼를 사용해서 입출력

package com.FileIO;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

// 4. byte 단위로 파일 입출력을 하자 버퍼를 써서
public class Test06 {
	public static void MyWrite(File f) throws IOException {
//		FileOutputStream fos = new FileOutputStream(f);
//		BufferedOutputStream bos = new BufferedOutputStream(fos);

//		OutputStream out = new OutputStream(f);
//		BufferedOutputStream bos = new BufferedOutputStream(out);

		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));

		bos.write("한글되나요~".getBytes());

		bos.close(); // bos가 닫힐 때 new FileOutputStream(f) 객체도 같이 닫힘
	}

	public static void MyRead(File f) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
		int res = 0;

		while ((res = bis.read()) != -1) {
			System.out.printf("%c", res);
		}
		bis.close();

	}

	public static void main(String[] args) {
		File f = new File("Test06.txt");
		try {
			MyWrite(f);
			MyRead(f);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

클래스 다이어그램
실행결과

클래스 다이어그램을 보고 클래스를 만들어 실행결과를 도출해라

 

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

Resize.java

public interface Resize {
	void setResize(int size);
}

 

Shape.java

public abstract class Shape {
	private int length;
	private int width;
	private String colors;

	public Shape() {
		super();
	}

	public Shape(int length, int width, String colors) {
		super();
		this.length = length;
		this.width = width;
		this.colors = colors;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public String getColors() {
		return colors;
	}

	public void setColors(String colors) {
		this.colors = colors;
	}

	public abstract double getArea();

}

 

Triangle.java

public class Triangle extends Shape implements Resize {

	public Triangle() {
		super();
	}

	public Triangle(int length, int width, String color) {
		super(length, width, color);
	}

	@Override
	public void setResize(int size) {
		super.setLength(size + super.getLength());
	}

	@Override
	public double getArea() {
		double area = super.getLength() * (double)super.getWidth() / 2;
		return area;
	}

}

 

Rectangle.java

public class Rectangle extends Shape implements Resize {

	public Rectangle() {
		super();
	}

	public Rectangle(int length, int width, String color) {
		super(length, width, color);
	}

	@Override
	public void setResize(int size) {
		super.setWidth(size + super.getWidth());
	}

	@Override
	public double getArea() {
		double area = super.getLength() * super.getWidth();
		return area;
	}

}

 

ShapeTest.java (main)

public class ShapeTest {

	public static void main(String[] args) {
		Shape[] sm = new Shape[6];

		sm[0] = new Triangle(7, 5, "Blue");
		sm[1] = new Rectangle(4, 6, "Blue");
		sm[2] = new Triangle(6, 7, "Red");
		sm[3] = new Rectangle(8, 3, "Red");
		sm[4] = new Triangle(9, 8, "White");
		sm[5] = new Rectangle(5, 7, "White");

		System.out.println("기본정보");
		System.out.println();
		String shapeType = null;

		for (int i = 0; i < sm.length; i++) {
			Shape s = (Shape) sm[i];

			if (s instanceof Triangle) {
				shapeType = "Triagnle";
			}

			if (s instanceof Rectangle) {
				shapeType = "Rectangle";
			}

			System.out.println(shapeType + "\t" + s.getArea() + "\t" + s.getColors());
		}

		System.out.println();
		System.out.println("사이즈를 변경 후 정보");
		System.out.println();

		for (int i = 0; i < sm.length; i++) {
			Shape s = (Shape) sm[i];

			if (s instanceof Triangle) {
				shapeType = "Triangle";
				((Triangle) s).setResize(5);
			}

			if (s instanceof Rectangle) {
				shapeType = "Rectangle";
				((Rectangle) s).setResize(5);
			}

			System.out.println(shapeType + "\t" + s.getArea() + "\t" + s.getColors());
		}
	}

}

Wrapper Class의 toString()

public class Test01 {
	public static void main(String[] args) {
//		== : 주소비교연산자
//		equals : new Car("bm7") == new Car("bm7")에서 "" 값을 비교하는?

		Integer i = new Integer(100);
		Integer i2 = new Integer("200");
		
		System.out.println(i);
		System.out.println(i2 + 10);
		System.out.println(i2.toString());
		
		Double d1 = new Double("97.7");
		System.out.println(d1 + 10);
		System.out.println(d1 + d1.toString());  // 그냥 d1은 숫자라 덧셈이 되는데 d1.toString()은 문자열이라 합치기가 되네
		
		Integer i3 = 100; // 이렇게 new Integer 없이 해도 알아듣는다.
		System.out.println(i3);
		
		double d4 = new Double(98.9);  // 이렇게 반대로 해도 안다 객체를 일반 자료형으로 형변환해서 객체에서 사용하는 함수를 쓸 수 없다.
		System.out.println(d4);  //  네트워크할 때는 클래스 단위로 주고받아야 한다. 기본자료형으로는 줄 수가 없음.
		
	}
}

 

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

String 클래스의 생성자함수

public class Test02 {

	public static void main(String[] args) {
//		String(String original) 아래 4개의 방식으로 하는 생성은 전부 옆에 생성자를 호출한다.
		String ori = "The String class represents character strings";
		String str02 = new String(ori);
		String str03 = new String(new String("The String class represents character strings"));
		String str04 = new String("The String class represents character strings");
		
		System.out.println(ori);
		System.out.println(str02);
		System.out.println(str03);
		System.out.println(str04);
		
		String res = ori.toUpperCase();
		System.out.println(res);

	}

}

 

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

String과 StringBuffer, StringBuilder의 차이

StringBuffer와 StringBuilder의 CRUD 함수

public class Test03 {

	public static void prn02() {
		// String = C
		// StringBuffer = C : append, insert // R : toString() // U : replace(int start,
		// int end, String str), setCharAt(int index, char ch)
		// D : delete(int start, int end), deleteCharAt(int index)
		// A thread-safe, mutable sequence of characters.

		// StringBuilder = C, R : , U , D

		StringBuffer sb = new StringBuffer(); // StringBuffer의 capacity는 초기값 16 이후 필요할때마다 18의 배수로 증가한다.
		System.out.println(sb.capacity()); // 16 => 34 => 70 => 142 => 286

//		sb.append("abc");
		for (int i = 65; i <= 80; i++) { // 65 ~ 80
			sb.append((char) i);
			System.out.println(i + " : " + sb.capacity());
		}

		System.out.println(sb);
		sb.delete(3, 6);
		System.out.println(sb);

	}

	public static void main(String[] args) {
		prn02();

	}

}

 

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

문제1. 자바 API에서 String 클래스에서 메서드를 찾아 문제 해결하기

// 문제 1) The String class represents character string.의 내용을 cnvr()메소드로 대입해서
// 대문자의 개수와 소문자의 개수를 출력하고 대문자를 소문자로, 소문자를 대문자로 변환 후 리턴받는다.

//1. String => char[] 메소드 찾아
//2. for -> character의 소문자인지 대문자인지 판별하는 메소드를 이용해서 조건문을 사용 후 cnt한다.
//character의 대문자로 소문자로 바꿔주는 메소드를 찾아서 변환
public class Exam01 {

	public static String cnvr(String str) {
		int lower = 0;
		int upper = 0;
		char[] new_str = str.toCharArray();

		for (int i = 0; i < new_str.length; i++) {
			if (Character.isLowerCase(new_str[i])) {
				lower++;
				new_str[i] = Character.toUpperCase(new_str[i]);
				continue;
			}
			if (Character.isUpperCase(new_str[i])) {
				upper++;
				new_str[i] = Character.toLowerCase(new_str[i]);
			}

		}
		System.out.println("upper : " + upper);
		System.out.println("lower : " + lower);

		return String.valueOf(new_str);
	}

	public static void main(String[] args) {
		String str = "The String class represents character string.";
		String res = cnvr(str);
		System.out.println(res);

	}

}

 

문제2. 

import java.util.Scanner;

// 문제 2) str을 받은 cnvr을 조작해보자
// 1. 전체를 대문자로 출력
// 2. 전체를 소문자로 출력
// 3. 공백을 제거 후 출력
// 4. 공백을 찾아 하트로 출력
// 5. 입력된 글자를 삭제 후 출력 = Scanner를 사용한다.
// 6. 문자열을 하나씩 바이트로 출력 getBytes
// 7. 문자열을 공백으로 분철해서 분철된 데이터를 출력
public class Exam02 {

	public static void cnvr(String str) {
		System.out.println("1. " + str.toUpperCase());
		System.out.println("2. " + str.toLowerCase());
		System.out.println("3. " + str.replace(" ", ""));
		System.out.println("4. " + str.replace(" ", "♥"));
		Scanner sc = new Scanner(System.in);
		String res = sc.next();
		sc.close();
		System.out.println("5. " + str.replace(res, " "));
		for (byte i : str.getBytes()) {
			System.out.println("6. " + i);
		}
		for (String i : str.split("\s")) {
			System.out.println("7. " + i);
		}

	}

	public static void main(String[] args) {
		String str = "The String class represents character string.";
		cnvr(str);
	}

}

[선언방법]
접근제한자[abstract] class user_name{
    멤버 (필드, 변수, 메소드)
}

생성자
1. 클래스이름과 동일하되 반환형 (return type)은 없다.
    ex) public class Test{
            public Test(){}  // 괄호안에 매개인자가 없으면 default 생성자
       }

2. overload 할 수 있다.
    ex) public class Test{
           public Test(){}  // 괄호안에 매개인자가 없으면 default 생성자
           public Test(int a, int b){}
           public Test(int a, double b){}
        }

3. 접근제한자를 이용하여 접근을 제한할 수 있다.

4. 객체를 생성할 때 자동으로 한 번만 호출된다. 메소드처럼 객체 주소번지로 명시호출 할 수 없다.
    Test t1 = new Test();
    Test t1 = new Test(10, 20); ==> X

    Test t1 = new Test();
    t1 = new Test(10, 20); ==> O

5. 생성자는 상속되지 않는다.

6. this() 형식으로 생성자간의 내부호출이 가능하다.
    ex) public class Test{
            private int a, b;
            public Test(){
               this(10, 20);
               this.a = 10;
                this.b = 20;
            }  // 이 멤버변수의 초기화 작업을 하고 있음
           public Test(int a, int b){
               this.a = a;
               this.b = b;
           }
    }
Test t1 = new Test(); // 멤버변수를 0으로 초기화 해놓고, 현재 오브젝트주소로 멤버변수값을 변경
// 내부호출할때 멤버변수를 0으로 초기화 하면서 현재 오브젝트주소로 멤버변수값을 변경
Test t2 = new Test( 10, 20 );

7. 생성자는 멤버변수를 초기화 하는 목적을 가진다. 

8. 모든 클래스는 반드시 생성자를 가지며 생성자를 명시하지 않을 때는 기본 생성자가 제공되어 호출되고 명시하게 되면 명시된 생성자가 호출된다.

 

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

자바의 상속
1. 자바는 클래스 간의 단일 상속을 원칙으로 한다.

2. this, super로 후손과 선조의 주소를 참조한다.

3. this(), super()로 후손과 선조의 생성자를 호출할 수 있다.

4. 생성자는 상속되지 않는다.

5. 접근제한자를 이용해서 선조는 후손에게 호출할 수 있는 접근을 제한할 수 있고
   abstract 키워드를 이용해서 강제적인 상속과 재정의를 할 수 있다.
   
6. 클래스 선언부에 final 이라고 명시되면 상속할 수 없다.

7. 객체의 생성 순서는 후손을 통해서 생성될 때 선조가 먼저 생성되고 후손이 나중에 생성된다.
   소멸은 역순으로 자동소멸이다.
   
8. 상속은 두 가지로 나뉜다. 클래스 간의 상속(단일), Interface(다중)=추상화 간의 상속이 있다. 

 

자바에서 표준 입출력을 구현하는 클래스가 있는데
표준입력을 할 때 3가지
    1. java.io 의 클래스 사용방법 : java.io.BufferedInputStream

    2. main() 매개인자로 입력받는 방법 : main(String[] args)

    3. Scanner 로 입력받는 방법 : java.util.Scanner

public class Test01 {
	
	public static String Prn(int jumsu) {
        int testscore = jumsu;
        char grade;

        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        return ("Grade = " + grade);
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);  // InputStream의 객체를 in으로 필드화 후 멤버로 가짐 = 표준입력장치
		System.out.println("input jumsu : ");
		int i = sc.nextInt();
		String res = Prn(i);
		System.out.println("res = " + res);
	}

}

 

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

for문 연습

public class Test03 {
    public static void for_test4() {
		System.out.println("case 4 : 중첩 for 출력");

		for (int i = 0; i < 5; i++) {
			for (int j = 1; j <= 5; j++) {
				System.out.printf("%5d", j + i * 5);
			}
			System.out.println();
		}
	}

	public static void for_test5() {
		System.out.println("case 5 : 중첩 for 출력");

		for (int i = 1; i < 6; i++) {
			for (int j = 0; j < 5; j++) {
				System.out.printf("%5d", j * 5 + i);
			}
			System.out.println();
		}
	}

	public static void for_test6() {
		System.out.println("case 6 : 중첩 for 출력");

		for (int i = 5; i > 0; i--) {
			for (int j = 0; j < 5; j++) {
				System.out.printf("%5d", i * 5 - j);
			}
			System.out.println();
		}
	}

	public static void for_test7() {
		System.out.println("case 7 : 중첩 for 출력");

		for (int i = 25; i > 20; i--) {
			for (int j = 0; j < 5; j++) {
				System.out.printf("%5d", i - j * 5);
			}
			System.out.println();
		}
	}

	public static void main(String[] args) {
		for_test4();
		for_test5();
		for_test6();
		for_test7();
        
    }
}

 

결과

case 4 : 중첩 for 출력
    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
case 5 : 중첩 for 출력
    1    6   11   16   21
    2    7   12   17   22
    3    8   13   18   23
    4    9   14   19   24
    5   10   15   20   25
case 6 : 중첩 for 출력
   25   24   23   22   21
   20   19   18   17   16
   15   14   13   12   11
   10    9    8    7    6
    5    4    3    2    1
case 7 : 중첩 for 출력
   25   20   15   10    5
   24   19   14    9    4
   23   18   13    8    3
   22   17   12    7    2
   21   16   11    6    1

 

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

for, if 연습

// 연습용 for, if
public class Test04 {
	public static void prn() {
		for (int i = 1; i <= 100; i++) {
			if (i % 10 == 0) {
				System.out.printf("%5s", "←");
				System.out.println();
			} else {
				System.out.printf("%5d", i);
			}
		}
	}

	// 2의 배수와 3의 배수 자리는 비워두자
	public static void prn2() {
		for (int i = 1; i <= 100; i++) {
			if (i % 10 == 0) {
				System.out.printf("%5s", "←");
				System.out.println();
			} else if ((i % 2 == 0) || (i % 3 == 0)) {
				System.out.printf("%5s", "X");
			} else {
				System.out.printf("%5d", i);
			}
		}
	}

	public static void main(String[] args) {
		prn();
		prn2();
	}
}

 

결과

    1    2    3    4    5    6    7    8    9    ←
   11   12   13   14   15   16   17   18   19    ←
   21   22   23   24   25   26   27   28   29    ←
   31   32   33   34   35   36   37   38   39    ←
   41   42   43   44   45   46   47   48   49    ←
   51   52   53   54   55   56   57   58   59    ←
   61   62   63   64   65   66   67   68   69    ←
   71   72   73   74   75   76   77   78   79    ←
   81   82   83   84   85   86   87   88   89    ←
   91   92   93   94   95   96   97   98   99    ←
   
    1    X    X    X    5    X    7    X    X    ←
   11    X   13    X    X    X   17    X   19    ←
    X    X   23    X   25    X    X    X   29    ←
   31    X    X    X   35    X   37    X    X    ←
   41    X   43    X    X    X   47    X   49    ←
    X    X   53    X   55    X    X    X   59    ←
   61    X    X    X   65    X   67    X    X    ←
   71    X   73    X    X    X   77    X   79    ←
    X    X   83    X   85    X    X    X   89    ←
   91    X    X    X   95    X   97    X    X    ←

 

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

자바의 배열 : 같은 데이터 타입의 값을 나열형으로 하나의 이름으로 등록해서 사용하는 것
                  서로 다른 데이터타입을 넣을 수 없다. 초기의 크기를 변경할 수 없다.

- 1차원 - length
    형식)
        데이터타입 변수명[] = {,,,,}
        데이터타입[] 변수명 = {,,,,}

        데이터타입[] 변수명 = new 데이터타입[요소의 크기];
        데이터타입[] 변수명 = new 데이터타입[]{,,,,};


-다차원
    형식)
        데이터타입 변수명[][] = {{},,,,}
        데이터타입[][] 변수명 = {{},,,,}
        데이터타입[] 변수명[] = {{},,,,}

        데이터타입[][] 변수명 = new 데이터타입[요소의 열의 크기][];

        데이터타입[] 변수명[] = new 데이터타입[요소의 열의 크기][];
        데이터타입 변수명[][] = new 데이터타입[]{{},,,,};

 

public class Test06 {
	public static void prn() {
		// 2,3을 만들자
		int[] ar[] = { { 10, 20, 30 }, { 40, 50, 60, 70 } };

		System.out.println(ar.length);
		System.out.println(ar[0].length);
		System.out.println(ar[1].length);

		for (int i = 0; i < ar.length; i++) {
			for (int j = 0; j < ar[i].length; j++) {
				System.out.printf("%5d", ar[i][j]);
			}
			System.out.println();
		}

		System.out.println("===========================");

		for (int[] a : ar) {
			for (int b : a) {
				System.out.printf("%5d", b);
			}
			System.out.println();
		}
	}
    
	public static void main(String[] args) {
        prn();
    }
}

 

결과

2
3
4
   10   20   30
   40   50   60   70
===========================
   10   20   30
   40   50   60   70

비정형DB인 MongoDB까지 배우고 Java로 다시 돌아온 이유는 이제 Hadoop과 Ecosystem을 배워야하는데

Hadoop이 Java를 기반으로 해서 그렇다. 또한 Hadoop은 Linux 환경에서 실행이 가능하기 때문에

앞으로 Java - Linux -Hadoop 순으로 진행될 것 같다.

 

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

공식문서 보는 법

1 -> 2-> 3 순으로 찾아가면 된다. 

1. package

2. package 내의 요소들 ( Interface, Classes)

3. 요소들의 자세한 설명

 

Summary에서 해당 요소가 무엇을 가지고 있는지 확인

상속관계 확인

final 여부 method의 static 여부 등 확인

final => 클래스앞 : 상속x, 메소드앞 : 재정의x, 변수앞 : 변수를 상수로 만든다. 변경x

 

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

1. 파일이름.java  ->  javac 파일이름.java  ->  파일이름.class

2. 자바의 실행 단위는 class 이다.

3. 자바의 접근제한자

  public -> protected(상속 공개) -> private -> default(같은 패키지 안에서는 공개)
  
4. 접근제한자는 클래스명, 메소드명, 멤버 변수 앞에 선언된다.

5. static, abstract 등도 접근제한자와 함께 선언된다.  

6. 기본자료형(byte, short, int, long, float, double, char, boolean) / 참조형(배열, 클래스)

데이터타입의 초기값

 

강의목표

1. java, WAS, IDE 설치하기

2. 서버를 실행시켜 파일을 실행하고 접속해보기

 

원래 java는 빅데이터에서 Hadoop에 들어가면서 배우는 커리큘럼이지만 파이썬 웹크롤링을 해보기 위해

먼저 설치하게 되었다.

 

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

java 설치

1. oracle.com에 접속해서 java를 다운받는다. (회원가입을 해야함)

java는 현재 16버전까지 나와있지만 8버전 이후로는 유료화 되었기 때문에 8버전을 다운받는다.

 

2. 다운받은 파일을 실행하여 java를 설치

 

3. 환경 변수에서 java를 전역 변수로 설정해준다. 

java가 설치된 폴더에서 java.exe와 코드를 컴파일하는 javac.exe를 확인할 수 있다.

 

cmd에서 java.exe를 실행해보면 어디서든 실행이 되지만 javac는 실행이 되지않으므로 전역변수를 설정해줘야 한다.

 

윈도우 탐색기에서 내 PC 우클릭 -> 속성 -> 고급 시스템 설정 -> 고급 탭의 환경 변수에서 시스템 변수에

새로 만들기를 클릭해서 자바가 설치된 경로를 JAVA_HOME이라는 변수로 저장해준다

 

시스템 변수의 path 항목을 편집하여 %JAVA_HOME%\BIN\을 추가해준다.

 

처음과는 다르게 javac도 잘 실행되는 것을 확인할 수 있다.

 

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

IDE설치

IDE는 대표적으로 사용되는 Eclipse를 사용한다.

 

1. eclipse.org에서 설치파일 다운받기

 

2. 다운받은 설치파일을 실행하여 설치하기

설치파일을 실행한 후 항목이 많이 뜨는데 우리는 웹서버를 실행하기 위해 설치하는 것이니 Web Developers로 설치

최신 Eclipse라 설치과정 중에 JRE 15를 연동할지 물어보는데 설치 후 Eclipse를 실행하여 java 1.8로 낮춰야한다.

 

3. 환경설정

Window - Preferences에서 설정창을 연다.

java 컴파일러의 버전이 Eclipse를 설치 과정중에 연동했던 버전인데 컴퓨터에 설치한 1.8로 낮춰준다.

 

jre의 경로도 java가 설치된 경로로 바꿔준다. jdk가 아님 주의

 

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

WAS(Web Aplication Server) 설치

WAS도 자주 사용되는 tomcat을 설치한다.

 

1. tomcat.apache.org에서 tomcat 9 다운

최신 버전은 tomcat 10이지만 9버전을 다운 받는다.

.exe로 받아서 설치할 경우 Eclipse에서 실행이 안된다고 하니 압축파일을 받아 풀어서 사용해야 한다.

 

2. 원하는 경로에 압축해제

 

3. Eclipse에 서버 연동

Preferences에서 Server - Runtime Environment에서 Add를 눌러 설치한 WAS(tomcat 9)를 추가해준다.

 

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

확인하기

 

1. Dynamic Web Project 생성

프로젝트 이름을 정해주고 Target Runtime에 설치한 WAS(Apache Tomcat v9.0)를 올릴 수 있으면 서버는 성공

Finish해서 프로젝트를 생성한다.

 

2. JRE확인

왼쪽의 메뉴에서 JRE 드롭다운 메뉴를 열었을 때 JRE가 설치된 폴더하위의 lib폴더에 있는 .jar파일과 이름이 같다면

jre도 1.8로 잘 연동이 되었다.

 

src/main/webapp 하위에 html파일을 하나 만들어 우클릭 -> Run As -> Run on Server를 해서 서버가 실행되고

웹페이지가 보인다면 확인 완료

+ Recent posts