Queue

import java.util.Queue;

import java.util.LinkedList;


public class QueueDemo {

public static void main(String[] args) {

String [] array = {"설운도", "이미자", "조성모", "나훈아"};

Queue<String> queue = new LinkedList<String>();

for(int i = 0 ; i < array.length ; i++)

queue.offer(array[i]);

System.out.println(queue.peek());

System.out.println(queue.poll());

System.out.println(queue.poll());

System.out.println(queue.poll());

System.out.println(queue.poll());

System.out.println(queue.poll());

}

}

출력:

설운도

설운도

이미자

조성모

나훈아

null

-------

bulk로 뽑으려면

System.out.println 부분을 빼고 

Iterator<String> iters = queue.iterator();

while(iters.hasNext()){

System.out.println(iters.next());

}

을 추가 해주면 한번에 출력이 가능하다

설운도

이미자

조성모

나훈아


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Generics


public class Demo<T> { //Generic Demo라고 선언

private T value;

public Demo(T value){

this.value = value;

}

public void setValue(T value){

this.value = value;

}

public T getValue(){

return this.value;

}

}


public class GenericDemo {

public static void main(String[] args) {

Demo<Integer> d = new Demo<Integer>(5); //Integer를 사용하는 Demo

d.setValue(10);

int num = d.getValue();

Demo<String> d1 = new Demo<String>("Hello");  //String을 사용하는 Demo

String value1 = d1.getValue();

Demo<Double> d2 = new Demo<Double>(89.5); //Double을 사용하는 Demo

double value2 = d2.getValue();

System.out.println(value1);

}

}

출력: Hello

generic은 인트형 더블형 스트링형등 모든 형을 처리할 수 있지만 label을 해줘야한다.

위에서 d1.setValue(89.5); 이렇게 써준다면 오류가 발생한다. String형에 89.5 를 써주어서.

----------------

import java.util.Stack;


public class GenericDemo1 {

public static void main(String[] args) {

Stack<String> mystack = new Stack<String>(); //mystack에는 스트링형만 넣을 수 있다.

mystack.push("Hello");

change(mystack);

}

static void change(Stack<String> s){

String msg = s.pop();

}

}

class Car{

String maker = "Kia";

}

//자바에서는 안전하게 하기위해서 형을 명확하게 써준다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

import java.util.LinkedList;

import java.util.Queue;

import java.util.Stack;

import java.util.Vector;


public class GenericDemo2 {

public static void main(String[] args) {

/*

Stack<String> stack = new Stack<String>();

stack.push("World");

Stack<Object> stack1 = stack; */ //에러발생. generic은 형번환이 되지 않는다.

//Queue<String> queue = new LinkedList<String>();  //<>사이에 있는 것이 형변환이 안되는 것이지 Queue와 LinkedList의 형변환은 된다.

Vector<Double> vecotr = new Stack<Double>(); //Generic 타입이 형변환이 안되는 것이지 객체가 형변환이 안되는 것은 아니다.

}

}

---------------------------------

import java.util.Stack;

import java.util.Vector;

public class GenericDemo3 {

public static void main(String[] args) {

Stack<String> stack = new Stack<String>();

stack.push("설운도"); stack.push("이미자");

print(stack);

}

static void print(Vector<String> v){ //String을 보냈는데 Vector가 받을 수 있다. 그러나 String이 바뀌면 안된다.

for(int i = 0 ; i < v.size(); i++) System.out.println(v.get(i));

}

}

출력:

설운도

이미자

----위 코드를 String형이 아닌 그냥 Stack으로 받으면

static void print(Stack s) { //raw type  - 형지정을 하지 않음.

System.out.println(s.pop());

System.out.println(s.pop());

}

안전하지 않다는 warning이 뜨지만 실행은 가능하다.

출력: 

이미자

설운도

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

import java.util.Stack;

import java.util.Vector;

public class GenericDemo3 {

public static void main(String[] args) {

Stack<Car> stack = new Stack<Car>();

stack.push(new Car());

print(stack);

}

static void print(Stack s) {

System.out.println(s.pop());

}

}

class Car{

String maker = "KIA";

}

출력:

Car@1c35ec 

이렇게 나오는데

-----이를 원하는 값을 얻기 위해 print를 아래와 같이 바꾸면 KIA가 출력된다.

static void print(Stack s) {

Car car = (Car)s.pop();

System.out.println(car.maker);

}

그러나 이는 좋은 방법이 아니다.

------------ print를 아래와같이 ?를 사용하는 방법.

static void print(Stack<?> s){  //?는 warning 안 뜨게 하는 역할이지 큰 역할은 없다.

Car car = (Car)s.pop();

System.out.println(car.maker);

}

형변환을 해야하는 것은 똑같지만 warning이 뜨지않는다. 

?자체는 의미가없지만 extends나 super를 써서 누구 이상이나 누구 이하로 제한 해야한다.

처음에썼던 Demo와 GenericDemo을 보면

public class Demo<T extends Number> ->Demo를 이렇게 쓰게되면 GenericDemo에서는 Stirng은 사용 불가하게 된다.

Number의 자식들만 사용할 수 있게되어서 int, double등 숫자형만 사용가능하게된다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

generic method는 리턴타입안에 또 무언가가 있는..

api에서 보면 sort를 찾아보면 public static <T> void sort(T[] a. Comparator< ? super T> c) 라고 쓰여진 것을 볼 수 잇다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ


public class GenericMethodDemo {

public static void main(String[] args) {

//Car [] array = new Car[3]; //Comparable의 자식이 아니라서 못넘어감.에러발생.

//sort(array);

String [] array = new String[]{"Hello","World","Java","Oracle"}; //Comparable의 자식이라서 넘어감

sort(array);

for(String str : array) System.out.println(str + "\t");

System.out.println();

Product [] array1 = new Product[4];

array1[0] = new Product("Notebook", 10_000_000);

array1[1] = new Product("Ballpen", 1_000);

array1[2] = new Product("Computer", 12_000_000);

array1[3] = new Product("Mouse", 50_000);

sort(array1);

for(Product p : array1) System.out.print(p + "\t");

}

static <T extends Comparable<T>> void sort(T [] array){ //comparable 자식들은 맘대로 사용할수 있는 만능 sort

for(int i = 0 ; i < array.length - 1 ; i++){

for(int j = 0 ; j < array.length - 1 - i; j++){

if(array[j].compareTo(array[j+1]) > 0){

T temp = array[j];

array[j] = array[j+1];

array[j+1] = temp;

}

}

}

}

}

class Product implements Comparable<Product>{

private String name;

private int price;

public Product(String name, int price){

this.name = name; this.price = price;

}

@Override

public String toString(){

return String.format("<%s, %,d>", this.name, this.price);

}

@Override

public int compareTo(Product p){

return this.price - p.price;

}

}

출력:

Hello

Java

Oracle

World


<Ballpen, 1,000> <Mouse, 50,000> <Notebook, 10,000,000> <Computer, 12,000,000>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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

Collection


import java.util.HashSet;

public class CollectionDemo {

public static void main(String[] args) {

//Object [] array = {new Car(), new Product("mouse", 50_000), 'A', 89.5, false, "Hello", 10}; //다양한 타입들을 한 배열에 넣을 수 있게 Object형 배열을 만들어줌.

String [] array = {"설운도","나훈아", "조용필", "이미자", "설운도"};

HashSet<String> set = new HashSet<String>();

for(int i = 0 ; i < array.length ; i++) set.add(array[i]);

System.out.println(set.size());

}

}

출력 :  4

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;

import java.util.TreeSet;

public class CollectionDemo {

public static void main(String[] args) {

String [] array = {"설운도","나훈아", "조용필", "이미자", "설운도"};

HashSet<String> hset = new HashSet<String>();

for(int i = 0 ; i < array.length ; i++) hset.add(array[i]);

System.out.println("<HashSet>"); print(hset);

TreeSet<String> tset = new TreeSet<String>();

for(int i = 0 ; i< array.length ; i++) tset.add(array[i]);

System.out.println("<TreeSet>"); print(tset);

}

static void print(Set<String> set){

Iterator<String> iters = set.iterator();

while(iters.hasNext()) System.out.print(iters.next() + "\t");

System.out.println();

}

}

출력:

<HashSet>

나훈아 이미자 조용필 설운도

<TreeSet>

나훈아 설운도 이미자 조용필

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

ArrayList

import java.util.ArrayList;


public class ArrayListDemo {

public static void main(String[] args) {

String [] array = {"설운도","나훈아", "조용필", "이미자", "설운도"};

ArrayList<String> list = new ArrayList<String>();

System.out.println("size = " + list.size());

for(int i = 0 ; i < array.length ; i++) list.add(array[i]);

for(int i = 0 ; i < array.length ; i++){

System.out.printf("%d --> %s\n", i, list.get(i));

}

//Iterator<String> iters = list.iterator();

//System.out.println("capacity = " + list.g);

}

}

출력:

size = 0

0 --> 설운도

1 --> 나훈아

2 --> 조용필

3 --> 이미자

4 --> 설운도

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Vector

예전 성적관리프로그램을 Vector로 바꾸면 (Vector는 받는 개수가 몇개인지 모른다)

Student.java


public class Student implements Comparable<Student>{

private String hakbun, name;

private int kor, eng, mat, edp, tot, ranking;

private double avg;

private char grade;

public Student(String hakbun, String name, int kor, int eng, int mat, int edp) {

this.hakbun = hakbun;

this.name = name;

this.kor = kor;

this.eng = eng;

this.mat = mat;

this.edp = edp;

this.ranking = 1;

}

@Override 

public int compareTo(Student s){

return this.getTot() - s.getTot();

}

@Override

public String toString(){

return String.format("%-10s%7s%5d%5d%5d%5d%5d%10.2f%5c%5d\n", this.hakbun, this.name, this.kor, this.eng, this.mat, this.edp, this. tot, this.avg, this.grade, this.ranking);

}

public int getTot() {

return tot;

}

public void setTot(int tot) {

this.tot = tot;

}

public int getRanking() {

return ranking;

}

public void setRanking(int ranking) {

this.ranking = ranking;

}

public double getAvg() {

return avg;

}

public void setAvg(double avg) {

this.avg = avg;

}

public char getGrade() {

return grade;

}

public void setGrade(char grade) {

this.grade = grade;

}

public int getKor() {

return kor;

}

public int getEng() {

return eng;

}

public int getMat() {

return mat;

}

public int getEdp() {

return edp;

}

}




Input.java

import java.io.File;

import java.io.FileNotFoundException;

import java.util.NoSuchElementException;

import java.util.Scanner;

import java.util.StringTokenizer;

import java.util.Vector;


import javax.swing.JFileChooser;

import javax.swing.JOptionPane;

public class Input {

private Scanner scan;

private Vector<Student> vector;

public Input(Vector<Student> vector){ 

this.vector = vector;

JFileChooser jc = new JFileChooser();

File file = null;

try{

if(jc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){  //확인버튼을 눌렀다면

file = jc.getSelectedFile();

this.scan = new Scanner(file);

}

}catch(FileNotFoundException ex){

JOptionPane.showMessageDialog(null, "File Not Found");

System.exit(-1);

}

}

public void input(){

StringTokenizer st = null;

String line = null;

try{

while((line = this.scan.nextLine()) !=null){

st = new StringTokenizer(line);

String [] array = new String[st.countTokens()];

int i = 0;

while(i < array.length){

array[i++] = st.nextToken();

}

Student student = new Student(array[0].trim(), array[1].trim(), Integer.parseInt(array[2].trim()),Integer.parseInt(array[3].trim()),Integer.parseInt(array[4].trim()), Integer.parseInt(array[5].trim()) );

this.vector.addElement(student); //학생 하나 만들어서 추가

}

}catch(NoSuchElementException ex){}

}

}


Calc.java

import java.util.Vector;


public class Calc {

private Vector<Student> vector;


public Calc(Vector<Student> vector) {

this.vector = vector;

}

public void calc(){

for(int i = 0 ; i < this.vector.size() ; i++){

Student s = this.vector.get(i);

s.setTot(s.getKor() + s.getEng() + s.getMat() + s.getEdp());

s.setAvg(s.getTot() /4 );

s.setGrade(this.getGrade(s.getAvg()));

}

}

private char getGrade(double avg){

if(avg<=100 && avg>=90 ) return 'A';

else if(avg<90 && avg>=80) return 'B';

else if(avg<80 && avg>=70) return 'C';

else if(avg<70 && avg>=60) return 'D';

else return 'F';

}

}



Sort.java

import java.util.Vector;


public class Sort {

private Vector<Student> vector;

public Sort(Vector<Student> vector) {

this.vector = vector;

}

public void sort(){

for(int i = 0 ; i < this.vector.size() - 1 ; i++){

for(int j = i+1; j < this.vector.size(); j++){

if(this.vector.get(i).compareTo(this.vector.get(j))>0){

this.vector.get(j).setRanking(this.vector.get(j).getRanking() +1);

}else if (this.vector.get(i).compareTo(this.vector.get(j))<0){

this.vector.get(i).setRanking(this.vector.get(i).getRanking() +1);

}

}

}

}

}



Output.java

import java.util.Vector;



public class Output {

private Vector<Student> vector;

public Output(Vector<Student> vector) {

this.vector = vector;

}

public void output(){

printLabel();

for(int i = 0 ; i < this.vector.size(); i++){

System.out.print(this.vector.elementAt(i));

}

}

private void printLabel(){

System.out.println("                             <<성적관리프로그램>>");

}

}



Main.java

import java.util.Vector;


public class Main {

public static void main(String[] args) {

Vector<Student> vector = new Vector<Student>(1,1); //1명들어올떄마다 크기를 1개씩만 증가.

Input input = new Input(vector);

input.input();

Calc calc = new Calc(vector);

calc.calc();

Sort sort = new Sort(vector);

sort.sort();

Output output = new Output(vector);

output.output();

}

}

출력:

                             <<성적관리프로그램>>

1101          한송이   78   87   83   78  326     81.00    B    6

1102          정다워   88   83   57   98  326     81.00    B    6

1103          그리운   76   56   87   78  297     74.00    C   10

1104          고아라   83   57   88   73  301     75.00    C    9

1105          사랑해   87   87   53   55  282     70.00    C   11

1106          튼튼이   98   97   93   88  376     94.00    A    1

1107          한아름   68   67   83   89  307     76.00    C    8

1108          더크게   98   67   93   78  336     84.00    B    4

1109          더높이   88   99   53   88  328     82.00    B    5

1110          아리랑   68   79   63   66  276     69.00    D   12

1111          한산섬   98   89   73   78  338     84.00    B    3

1112          하나로   89   97   78   88  352     88.00    B    2

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Hashtable


import java.util.Date;

import java.util.Hashtable;

import java.util.StringTokenizer;


public class HashtableDemo {

public static void main(String[] args) {

Date now = new Date();

//System.out.println(now);

StringTokenizer st = new StringTokenizer(now.toString());

//Mon Mar 24 16:34:53 KST 2014

String [] array = new String[st.countTokens()];

int i = 0 ;

while(i < array.length) array[i++] = st.nextToken();

System.out.print("오늘은 " + array[5] + "년 " + getMonth(array[1]) + "월 " + array[2] + "일입니다.");

}//오늘은 2014년 Mar월 24일입니다. 이렇게 나오는 것을 해결하기 위해 아래를 추가.

static int getMonth(String month){ //해쉬 테이블은 DB역할. 키로 값을 뽑아내는.

Hashtable<String, Integer> ht = new Hashtable<String, Integer>();

ht.put("Jan", new Integer(1)); ht.put("Feb", new Integer(2));

ht.put("Mar", new Integer(3)); ht.put("Apr", new Integer(4));

ht.put("May", new Integer(5)); ht.put("Jun", new Integer(6));

ht.put("July", new Integer(7)); ht.put("Aug", new Integer(8));

ht.put("Sep", new Integer(9)); ht.put("Oct", new Integer(10));

ht.put("Nov", new Integer(11)); ht.put("Dec", new Integer(12));

return ht.get(month);

}

}

출력:

오늘은 2014년 3월 24일입니다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Porperties

//Properties는 hashtable의 자식이다. 키와 값을 모두 가지고 있다.

import java.util.Enumeration;

import java.util.Properties;


public class PropertiesDemo {  

public static void main(String[] args) {

Properties props = System.getProperties();

//키

Enumeration<Object> keys = props.keys();

while(keys.hasMoreElements()){

String key = (String)keys.nextElement();

System.out.printf("%s --> %s\n", key, System.getProperty(key));

}

//값

/*Enumeration<Object> enums = props.elements();

while(enums.hasMoreElements()){

Object obj = enums.nextElement();

System.out.println(obj);

}*/

}

}

출력은 영어로 시스템에 대한 정보(키or값)이 나온다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

dbinfo.properties 텍스트파일


DBDRIVER=oracle.jdbc.driver.JdbcDriver

DBURL=jdbc:oracle:thin:@127.0.0.1:1521:orcl

DBUSER=scott

DBPWD=tiger



PropertiesDemo1.java


import java.io.FileReader;

import java.util.Properties;


public class PropertiesDemo1 {

public static void main(String[] args) throws Exception{

Properties props = new Properties();

FileReader fr = new FileReader("dbinfo.properties");

props.load(fr);

System.out.println("Driver Name : " + props.getProperty("DBDRIVER"));

System.out.println("Driver URL : " + props.getProperty("DBURL"));

System.out.println("User : " + props.getProperty("DBUSER"));

System.out.println("Password : " + props.getProperty("DBPWD"));

}

}

출력:

Driver Name : oracle.jdbc.driver.JdbcDriver

Driver URL : jdbc:oracle:thin:@127.0.0.1:1521:orcl

User : scott

Password : tiger



자식의 exception의 개수와 범위는 부모보다 작아야한다.

import java.io.FileNotFoundException;


public class ExceptionDemo {

public static void main(String[] args) {


}

}

class Bumo{

public void display() throws FileNotFoundException{ 

throw new FileNotFoundException();

}

}

class Jasik extends Bumo{

@Override

public void display() throws FileNotFoundException, CloneNotSupportedException {  //자식은 부모의 checked exception을 안 던져도되고, 같은 것을 던져도된다.

if(true) throw FileNotFoundException(); 

else throw new CloneNotSupportedException();  //그러나 자식은 부모보다 더많은 exception을 던질 수 없다.

} //이 코드에서는 부모는 한개의 exception을 던졌으나 자식은 두개를 던져서 오류발생.

}//그리고 자식의 exception의 범위도 부모보다 더 커서는 안된다. 부모가 RuntimeException을 던지고 자식이 Exception을 던지면 오류발생.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Assertion

exception을 표현하면 아래와 같다.

import java.util.Scanner;


public class AssertionDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int num = 0;

try{

System.out.println("Input a integer number(0~10) :");

num = scan.nextInt();

if(num < 0 || num > 10) throw new Exception("0부터 10까지입니다");

}catch(Exception ex){

javax.swing.JOptionPane.showMessageDialog(null, ex.getMessage());

}

}

}

이코드를 Assertion으로 바꾸면 아래와 같다.

import java.util.Scanner;


public class AssertionDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int num = 0;

System.out.println("Input a integer number(0~10) :");

num = scan.nextInt();

assert(num >= 0 && num <= 10) : "num = " + num; //참이면 통과해서 다음라인을 실행하고, 거짓이면 :뒤를 실행.

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

}

}

만약 그냥 이클립스에서 실행하면 12를 넣어도 System.out.println("num = " + num); 라인을 수행한다.

그러나 기본적으로 이클립스에서는 Assertion처리를 안해주기 때문에 무조건 다음라인을 수행한다.

여기서 run configuration에서 argument 탭에서 VM arguments 에 -ea를 넣어주면 assertion 처리를 해준다. 

그럼 아래와 같이 출력됨을 볼 수있다.

Input a integer number(0~10) :

12

Exception in thread "main" java.lang.AssertionError: num = 12

at AssertionDemo.main(AssertionDemo.java:9)

----------------------------------

public class AssertionDemo1 {

public static void main(String[] args) {

int i , sum = 0;

for(i=0; i<100 ; i++)

sum += i;

assert(i == 10) : "10번 돌지 않았음";

System.out.println("계속 진행");

}

}

역시 위 처럼 assertion 처리를 위해 -ea를 추가 시켜주어 실행하면 i=10이 맞으므로 "계속 진행" 을 출력한다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

exceptino은 소비자 관점으로 처리하고, assertion은 개발자관점.

파라미터로 들어오는 값은 exception처리를 하고, 13월이 들어오는 것 같은 경우는 assertion으로 처리하자.

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

Wrapper

자바 1.5 이전

public class WrapperDemo {

public static void main(String[] args) {

int num = 9;  //num=9가 stack에 생김.

Integer in = new Integer(num); //boxing, wrapping //num을 stack에서 heap으로 보내줌(heap은 객체만 가지고 있어야하므로)

int su = in.intValue();//unboxing, unwrapping //다시 num을 stack으로 보내려면 unwrap해야한다.

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

}

}

출력: su = 9

-------------

자바 1.5부터는 auto wrapping, auto unwrapping을한다


public class WrapperDemo {

public static void main(String[] args) {

int num = 9;

Integer in = num + 100; //auto boxing//왼쪽은 참조변수,오른쪽은 값변수이다. new Integer(num).intValue() + 100 을 했어야했는데.

int su = in * 5;  //auto unboxing//in은 참조변수인데(주소를 가지고 있는데), su(값 변수)에 넣으라니?? 과거에는 이모든게 택도없었다.

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

}

}

출력 : su = 545

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

진수 변환

public class WrapperDemo1 {

public static void main(String[] args) {

String strNum = "128";

System.out.println("10진수 = " + Integer.parseInt(strNum));

System.out.println("8진수 = " + Integer.toString(Integer.parseInt(strNum), 8));

System.out.println("16진수 = " + Integer.toString(Integer.parseInt(strNum), 16));

System.out.println("2진수 = " + Integer.toString(Integer.parseInt(strNum), 2));

}

}

출력:

10진수 = 128

8진수 = 200

16진수 = 80

2진수 = 10000000

------------------------

public class WrapperDemo1 {

public static void main(String[] args) {

int su = 5;

//Integer in = new Integer(su);

Integer in = Integer.valueOf(su); //생성자를 쓰지않고, valueOf 메소드 사용

double avg = in.doubleValue();

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

}

}

출력 : avg = 5.0

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Math - ceil(올림), floor(내림), round(반올림)

public class WrapperDemo1 {

public static void main(String[] args) {

double avg = 89.45678;

System.out.println("ceil() : " + Math.ceil(avg));

System.out.println("floor() : " + Math.floor(avg));

System.out.println("round() : " + Math.round(avg));

}

}

출력 :

ceil() : 90.0

floor() : 89.0

round() : 89

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

String

String replace (char oldChar, char newChar)


public class StringDemo {

public static void main(String[] args) {

String str = "Hello";

str = str.replace('H', 'C');  //새주소를 할당해야 바뀐다. 스트링은 절대 값이 바뀌지 않는다.

System.out.println(str);

}

}

출력:

Cello

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

String은 새주소 할당하는데 시간이 소모하기 떄문에 String Buffer를 사용할 대보다 시간을 더 소모한다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

System class

public class SystemDemo {

public static void main(String[] args) {

//System.out.println("Now is " + System.currentTimeMillis());

/*long current = 1395371852900L; //currentTimeMillis로 가져온 숫자

java.util.Date d = new java.util.Date(current); //Date는 위에서 가져온 숫자를 년월일시분초로 바꿔줌.

System.out.println(d);*/

System.out.println("Login User : " + System.getProperty("user.name")); //유저이름을 주세요.

System.out.println("OS name : " + System.getProperty("os.name"));  //os이름을 주세요.

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Runtime class


public class RuntimeDemo {

public static void main(String[] args) throws Exception{

//Runtime r = new Runtime(); //Demo 클래스와 비슷한 이유??? new 사용불가

Runtime r = Runtime.getRuntime();

r.exec("gnome-system-monitor");

}

}

class Demo{ // 멤버들이 모두 static. 이러한 클래스를 유틸리티클래스.

private Demo(){} //생성자를 private으로 만들어 버리게 되어 new를 못쓴다.

public static final int SU = 5;

public static void display(){

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

}

}


실행하면 gnome-system-monitor 를 실행한다.

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

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Class Library java.util package


stack - Last In First Out


import java.util.Stack;

public class StackDemo {

public static void main(String[] args) {

Stack<String> stack = new Stack(); //string을 담는 stack을 만들어줌.

String [] array = {"설운도", "조성모", "이미자", "김광석"};

for(int i = 0 ; i < array.length ; i++)  stack.push(array[i]);

//System.out.println(stack.peek()); //peek는 가리키기만하고

//System.out.println(stack.pop());  //heap은 가리키는 것을 뽑아냄.

while(!stack.empty()) System.out.println(stack.pop()); //데이터가 더이상 없을때 pop을 더이상 실행하지 않게 하기 위해

}

}

출력:

김광석

이미자

조성모

설운도

----------------------------

통으로 출력. 그래서 순서가 바뀌지않음.

import java.util.Stack;

import java.util.Enumeration;


public class StackDemo {

public static void main(String[] args) {

Stack<String> stack = new Stack(); //string을 담는 stack을 만들어줌.

String [] array = {"설운도", "조성모", "이미자", "김광석"};

for(int i = 0 ; i < array.length ; i++)  stack.push(array[i]);

Enumeration<String> enums = stack.elements();

while(enums.hasMoreElements())

System.out.println(enums.nextElement());

}

}

출력:

설운도

조성모

이미자

김광석


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

StringTokenizer 사용.

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

import java.util.StringTokenizer;


import javax.swing.JFileChooser;

import javax.swing.JOptionPane;


public class StringTokenizerDemo {

public static void main(String[] args) {

File file = null;

Scanner scan = null;

JFileChooser jc = new JFileChooser();

jc.showOpenDialog(null);

int state = jc.showOpenDialog(null);

try{

if(state == JFileChooser.APPROVE_OPTION){

file = jc.getSelectedFile();

scan = new Scanner(file);

String line = scan.nextLine();

//String [] array = line.split("\\s+"); //split 사용하여 문자열자르기.

StringTokenizer st = new StringTokenizer(line);  //space bar 기준으로 파싱

String [] array = new String[st.countTokens()];

for(int i = 0 ; i< array.length ; i++)

array[i] = st.nextToken();

System.out.printf("%s, %s, %s, %s, %s, %s\n", array[0], array[1], array[2], array[3], array[4], array[5]);

}

}catch(FileNotFoundException ex){

JOptionPane.showMessageDialog(null,  "File Not Found");

System.exit(-1);

}finally{

scan.close();

}

}

}

출력: (파일을 선택하여)

1101, 한송이, 78, 87, 83, 78

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Random class

import java.util.Random;


public class RandomDemo {

public static void main(String[] args) {

//int rand = (int)(Math.random() * 6 + 1); //1~6까지 랜덤값 출력하는 방법1.

Random r = new Random();

int rand = r.nextInt(6) + 1; //nextInt(최대값) + 최소값

System.out.println(rand);

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

//자바에서 날짜 시간 처리하는 방법 1

import java.util.Date;

public class DateDemo {

public static void main(String[] args) {

Date now = new Date();

System.out.println(now);  //now.toString()

}

}

출력: Fri Mar 21 14:36:37 KST 2014

-----------

//자바에서 날짜 시간 처리하는 방법 2

 import java.util.Calendar;


public class CalendarDemo {

public static void main(String[] args) {

Calendar cal = Calendar.getInstance();

System.out.printf("%d년 %d월 %d일입니다\n", cal.get(Calendar.YEAR), (cal.get(Calendar.MARCH)+1), cal.get(Calendar.DATE));

//cal.get(Calendar.DAY_OF_MONTH); 이렇게 써도 됨.

}

}

출력 : 2014년 3월 21일입니다

------------

//자바에서 날짜 시간 처리하는 방법 3

import java.util.Calendar;

import java.util.GregorianCalendar;


public class GregorianCalendarDemo {

public static void main(String[] args) {

Calendar cal = new GregorianCalendar(2012, 1, 1);  //2012년 2월 1일

switch(cal.get(Calendar.DAY_OF_WEEK)){

case 1 : System.out.println("SUN"); break;

case 2 : System.out.println("MON"); break;

case 3 : System.out.println("TUE"); break;

case 4 : System.out.println("WED"); break;

case 5 : System.out.println("THU"); break;

case 6 : System.out.println("FRI"); break;

case 7 : System.out.println("SAT"); break;

}

System.out.println(cal.getActualMaximum(Calendar.DAY_OF_MONTH));  //그 달에 몇일까지있는지

}

}

출력: (2012는 윤년이므로)

WED

29

-----------------------

//자바에서 날짜 시간 처리하는 방법 4

public class FormatterDemo {

public static void main(String[] args) {

System.out.printf("Now is %1$tY-%1$tm-%1$td %1$tA %1$tH:%1$tM:%1$tS\n", new java.util.Date()); //대문자 Y를 쓸지 소문자 y를 쓸지 헷갈리기 떄문에 api 에서 formatter 찾아줌. 

}//갯수만큼 받아줘야하나 그것을 안쑤주기 위하여 1$를 붙여줌.

}

출력 : Now is 2014-03-21 Friday 15:02:46

//fmt.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") -> " d c b a"    - 숫자$의 사용..?

-----------------------

//자바에서 날짜 시간 처리하는 방법 5

import java.text.DateFormat;

public class DateFormatDemo {

public static void main(String[] args) {

DateFormat df = DateFormat.getDateTimeInstance(

DateFormat.FULL,  //날은 자세하게

DateFormat.SHORT  //시는 짧게

);

System.out.println(df.format(new java.util.Date()));

}

}

출력:

Friday, March 21, 2014 3:08 PM

---------------------

//자바에서 날짜 시간 처리하는 방법 6

import java.text.DateFormat;

import java.text.SimpleDateFormat;


public class SimpleDateFormatDemo {  //api에서 simpleDateFormat을 참조

public static void main(String[] args) {

String pattern = "지금은 yyyy년 MM월 dd일 HH시 mm분 ss초";

DateFormat df = new SimpleDateFormat(pattern);

System.out.println(df.format(new java.util.Date()));

}

}

지금은 2014년 03월 21일 15시 13분 07초


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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

음반판매 프로그램

Account.java

public class Account {

private int bunho;  //소매점번호

private String code;  //음악종류코드

private int su;         //판매수량

public Account(int bunho, String code, int su) {

this.bunho = bunho;

this.code = code;

this.su = su;

}

public int getBunho() {

return bunho;

}

public String getCode() {

return code;

}

public int getSu() {

return su;

}

}



Janre.java

public class Janre {

private String janreCode;  //쟝르코드 for 소팅

private String name;  //쟝르이름

private int kyonggi;      //경기지역판매액

private int youngnam;   //영남지역판매액

private int choongchung;   //충청지역판매액

private int num;                //판매량

public String getJanreCode(){

return this.janreCode;

}

public void setJanreCode(String janreCode){

this.janreCode = janreCode;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getKyongi() {

return kyonggi;

}

public void setKyonggi(int kyonggi) {

this.kyonggi = kyonggi;

}

public int getYoungnam() {

return youngnam;

}

public void setYoungnam(int youngnam) {

this.youngnam = youngnam;

}

public int getChoongchung() {

return choongchung;

}

public void setChoongchung(int choongchung) {

this.choongchung = choongchung;

}

public int getNum() {

return num;

}

public void setNum(int num) {

this.num = num;

}

}



Main.java

public class Main {

public static void main(String[] args) {

Account [] array = new Account[7];

Input input = new Input(array);

int count = input.input();

Janre [] array1 = new Janre[4];

Calc calc = new Calc(array, array1, count);

calc.calc();

Sort sort = new Sort(array1);

sort.sort();

Output out = new Output(array, array1, count);

out.display();

}

}



Input.java

import java.util.Scanner;


public class Input {

private Account [] array;

private Scanner scan;

public Input(Account [] array){

this.array = array;

scan = new Scanner(System.in);

}

public int input(){

int count = 0;

char y_n = '\0';

do{

count++;

int no = 0;

do{

System.out.print("소매점번호(1 ~ 99) : ");

no = this.scan.nextInt();

}while(no < 1 || no > 99);

String code = null;

do{

System.out.print("음악종류코드(K1 | K2 | K3 | K4) : ");

code = this.scan.next();

}while(code.charAt(0) != 'K' || code.charAt(1) < 49 || code.charAt(1) > 52);

int su = 0;

do{

System.out.print("판매수량(1 ~ 99) : ");

su = this.scan.nextInt();

}while(su < 1 || su > 99);

System.out.print("입력/출력(I/O) : ");

y_n = this.scan.next().charAt(0);

this.array[count - 1] = new Account(no, code, su);

}while(count <= 7 && (y_n == 'i' || y_n == 'I'));

return count;

}

}



Calc.java

public class Calc {

private Account [] array;

private int count;

private Janre [] array1;

public Calc(Account [] array, Janre [] array1, int count){

this.array = array;

this.count = count;

this.array1 = array1;

initJanre();     //쟝르이름초기화

}

private void initJanre(){

String [] codeArray = {"K1", "K2", "K3", "K4"};

String [] codeNameArray = {"팝송", "가요", "가극", "째즈"};

for(int i = 0 ; i < this.array1.length ; i++){

this.array1[i] = new Janre();

this.array1[i].setJanreCode(codeArray[i]);

this.array1[i].setName(codeNameArray[i]);

}

}

public void calc(){

for(int i = 0 ; i < this.count ; i++){

int bunho = this.array[i].getBunho();

String code = this.array[i].getCode();

int su = this.array[i].getSu();

if(bunho > 0 && bunho <= 35) 

setKyonggi(code, su);

else if(bunho > 35 && bunho <= 75)

setYoungnam(code, su);

else if(bunho > 75 && bunho < 100)

setChoongchung(code, su);

setNum(code, su);

}

}

private void setKyonggi(String code, int su){ //경기지역계산

//49:1, 50:2, 51:3, 52:4

int kind = code.charAt(1);

int kyonggi = this.array1[kind - 49].getKyongi();

int danga = getDanga(code);

kyonggi += su * danga;

this.array1[kind - 49].setKyonggi(kyonggi);

}

private void setYoungnam(String code, int su){ //영남지역계산

//49:1, 50:2, 51:3, 52:4

int kind = code.charAt(1);

int youngnam = this.array1[kind - 49].getYoungnam();

int danga = getDanga(code);

youngnam += su * danga;

this.array1[kind - 49].setYoungnam(youngnam);

}

private void setChoongchung(String code, int su){ //충청지역계산

//49:1, 50:2, 51:3, 52:4

int kind = code.charAt(1);

int choongchung = this.array1[kind - 49].getChoongchung();

int danga = getDanga(code);

choongchung += su * danga;

this.array1[kind - 49].setChoongchung(choongchung);

}

private int getDanga(String code){

//49:1, 50:2, 51:3, 52:4

int kind = code.charAt(1);

int danga = 0;

switch(kind){

case 49 : danga = 100; break;

case 50 : danga = 300; break;

case 51 : danga = 400; break;

case 52 : danga = 200; break;

}

return danga;

}

private void setNum(String code, int su){  //총합계판매량

//49:1, 50:2, 51:3, 52:4

int kind = code.charAt(1);

int num = this.array1[kind - 49].getNum();

this.array1[kind - 49].setNum(num + su);

}

}



Sort.java


public class Sort {

private Janre [] array;

public Sort(Janre [] array){

this.array = array;

}

public void sort(){

int i, j;

Janre key;

for(i = 1 ; i < this.array.length; i++){

key = this.array[i];

for(j = i - 1 ; 

j >= 0 && this.array[j].getJanreCode().charAt(1) > key.getJanreCode().charAt(1); 

   j--){

this.array[j + 1] = this.array[j];

}

this.array[j+1] = key;

}

}

}



Output.java

public class Output {

private Account [] array;

private Janre [] array1;

private int count;

public Output(Account [] array, Janre [] array1, int count){

this.array = array;

this.array1 = array1;

this.count = count;

}

public void display(){

int total = 0;

System.out.println("\n\n\n");

System.out.println("                        <<지역별 음반 판매 관리 프로그램>>");

writeDash();

System.out.println("종류         경기지역판매액       영남지역판매액       충청지역판매액        판매량");

writeDash();

for(int i = 0 ; i < this.array1.length ; i++){

System.out.printf("%s\t%,15d%,20d%,20d%15d\n",

this.array1[i].getName(), this.array1[i].getKyongi(),

this.array1[i].getYoungnam(), this.array1[i].getChoongchung(),

this.array1[i].getNum());

total += this.array1[i].getNum();

}

writeDash();

System.out.println("\n");

System.out.println("총합계판매량 : " + total);

System.out.println("\n입력데이터");

write();

}

private void writeDash(){

for(int i = 0 ; i < 70 ; i++) System.out.print("-");

System.out.println();

}

private void write(){

for(int i = 0 ; i < this.count ; i++){

System.out.printf("%d\t%s\t%d\n", 

this.array[i].getBunho(), this.array[i].getCode(),

this.array[i].getSu());

}

}

}





import static java.lang.System.out;  

import static java.lang.Integer.parseInt;  //주의할 점. 1. parseInt는 메소드임에도 ()를 붙이지 않는다.

public class PackageImportDemo{

public static void main(String[] args) {

java.lang.System.out.println("Hello"); //풀네임. 그러나 java lang을 안써줘도 되기에

System.out.println("Hello");

out.println("Hello");  //위에 import해주어 짧게 써줄 수 있다.

//int result = java.lang.Integer.parseInt("5");  //java.lang은 생략.

int result = parseInt("5");  //위에 import해주어 짧게 써줄수 있다.

}

//static int parseInt(String str){}  //2.parseInt가 이름 충돌이 나는 것을 조심해야함.

}


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

AccessModifierDemo 4가지

public 만 보인다.

protected - 부모 자식 관계가 아니라서 보이지 않는다.

default - 같은 폴더에 위치하지 않아서 보이지 않는다.


package com.naver.libs.HR;

public class Insa {

private int num = 10;

double avg = 89.5;

protected char grade = 'A';

public String name = "Sally";

}


import com.naver.libs.HR.Insa;

public class AccessModifierDemo extends Insa {

public static void main(String[] args) {

AccessModifierDemo amd = new AccessModifierDemo();

amd. //까지 쓰면 name 과 grade까지만 쓸 수 있다. (부모자식관계이기 때문에)

}//만일 부모자식관계가아니고, Insa를 메모리에올리면 오직 public인 name만 접근 가능하다.

}

------

여기서 class의 접근제한자는 두개밖에 없다. class Insa 와 public class Insa만 쓸 수 있다. private과 protected는 사용 불가하다.

폴더안에서 접근하려면 default, 밖에서 접근하려면 public. 권한은 항상 제한해야하므로, public default 사용이 둘다 가능하면 default를 사용한다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

//static variable

public class StaticDemo {

public static void main(String[] args) {

Demo [] array = new Demo[3];

for(int i = 0 ; i < array.length; i++)

array[i] = new Demo();

for(Demo d : array)

System.out.println(d);

}

}


public class Demo {

int su;

static int num;

public Demo(){

this.su++;

num = this.su;

}

@Override

public String toString(){

return String.format("su = %d, num = %d\n",  su, num);

}

}


출력:

su = 1, num = 1


su = 1, num = 1


su = 1, num = 1

new Demo로 항상 초기화된 값을 가지고 시작한다.

------여기서 Demo를 아래와 같이 바꿔주면

public Demo(){

this.su++;

num++;

}

출력:

su = 1, num = 3


su = 1, num = 3


su = 1, num = 3

num은 static이기 때문에 저장되는 위치가 다르다. 값이 변하면 변한 값을 계속 가지고 있는다. 그래서 마지막 값인 3을 계속 가지고 출력한다.

-----------------------------------------------

//public method


public class StaticDemo1 {

private static int num = getNum(); //메인보다 먼저 실행되어 num의 초기화 실행. 

private static int getNum(){

System.out.println("나는 스태틱 메소드");

return 100;

}

public static void main(String[] args) {

System.out.println("나는 메인 메소드");

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

}

}

//static method를 쓰는 이유는 주소없이 접근하기 위해서이다.

출력:

나는 스태틱 메소드

나는 메인 메소드

num = 100


------------------------------------------------

static initializers


public class StaticDemo2 {

private int num;  //member variable  //생성자가 num을 초기화 시켜준다.

private static double avg; //static variable  

{ //member initialization block

num = 100;

System.out.println("Called \"member initialization block\"");

}

static {  //static initializer  //두번 호출 할 수없다.

avg = 89.5;

System.out.println("Called \"static initializer\"");

}

public static void main(String[] args) {

System.out.println("Called \"main method\"");

StaticDemo2 sd = new StaticDemo2(); //추가

}

}

//static variable이 가장먼저 메모리에 올라온다. 그래서 static initializer가 가장 먼저 실행된다.

//member initialization block 은 실행되지 않았는데 이것을 실행되게 하려면 생성자를 써줘야한다. 그래서 main의 2번째 줄을 추가해줬다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Final

//final variable --> constant

public class FinalDemo {

private final int NUM;  //member constant

private static final double PI;  //static constant

static{  //static initializer

PI = 3.141596;  ////스태틱 상수 초기화

}

/*public FinalDemo(){  //constructor

this.NUM = 10000;  //멤버상수의 초기화

}*/

//위 혹은 아래 중 하나로 멤버상수를 초기화 시켜줌.

{  //member initializer   

this.NUM = 10000;

}

public static void main(String[] args) {

final String name = "Sally";  //local constant

}

}

-------------------

final을 method에 쓸 때


public class FinalDemo1 {

public static void main(String[] args) {

/*Bumo b = new Jasik();

b.display();*/ //부모의 display method를 final로 해주어서 이런식으로 만들어주면 자식의 display 메소드를 사용하지 못한다.

Jasik ja = new Jasik();  //상속의 기능을 이용하여 자식을 통하여 부모의 display, 자식의 display 메소드를 접근 가능하게한다.

ja.display(); ja.display(5);

}

}

abstract class Bumo{

public final void display() { System.out.println("나는 부모의 메소드"); } //메소드를 final로 만들면 자식메소드는 오버라이드할 수없다.

}

class Jasik extends Bumo{

/*@Override

public void display() { System.out.println("나는 부모의 메소드"); }*/

public void display(int su) { System.out.println("나는 자식의 메소드"); }  //부모 display method가 final로 해주어서 int su를 추가하여 오버로딩으로 바꿔줌.

}

출력:

나는 부모의 메소드

나는 자식의 메소드

--------------------------ㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class FinalDemo2 {

public static void main(String[] args) {

Parent p = new Child(); 

p.display(); //자식의 메소드

p.print(); //부모의 메소드

}

}

class Parent{

public void display() { System.out.println("Called display()");}

public final void print() { System.out.println("Called print()");}

}

class Child extends Parent{

@Override

public void display() { System.out.println("Child's Called display()"); }

}

출력:

Child's Called display()

Called print()

//만약 class Parent를 -> final class Parent로 바꿔주면 자식을 가질 수없다.

//final class와 abstract class는 상극. abstract class는 자식을 낳아야만하는 class이고, final class 는 자식을 못낳는 class.

//그래서 final class 와 abstract class 는 동시에 사용이 불가능하다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Deprecation


public class DeprecationDemo {

public static void main(String[] args) {

java.util.Date now = new java.util.Date();

int year = now.getYear();

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

}

}

//getYear부분이 중간이 줄이 그어져 있고 warning이 뜬것을 볼 수있다.

위코드를 터미널에서 컴파일하면 javac DeprecationDemo.java 를 쓰면 warning이 든다. 이유를 알아보면 -Xlint를 써도되지만

javac -deprecation DeprecationDemo.java를 쓰면  getYear 떄문인 것을 알 수 있다. 

API에서 보면  Calendar.get(Calendar.YEAR) - 1900 이렇게 나왔는데,  이는 저렇게 쓰고 1900을 빼면 원래나오는 수가 나온다고 의미.

---------------------

import java.awt.Color;

import java.awt.Frame;


public class DeprecationDemo1 {

private Frame f;

private void display(){

f = new Frame("Frame Demo");

f.setSize(400,300);

f.setBackground(Color.YELLOW);

f.show();

}

public static void main(String[] args) {

new DeprecationDemo1().display();

}

}

//여기서 show부분이 위코드의 getYear과 같이 글자 중간에 줄이 그어져 있고 warning이 뜬 것을 볼 수있다.

출력: 노랑색창이 하나뜸. 닫혀지지않음. 종료 이벤트를 안만들어줘서..

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

/*

 * Nested Class --> static class

 * 1. 생성방법: Outer class 의 이름으로 생성(outer class의 주소 불필요)

 * 2. 사용목적: 

 * 3. 제한사항: Outer class의 멤버변수와 멤버메스드 접근 안됨.

 */

public class NestedClassDemo {

public static void main(String[] args) {

Outer.Inner in = new Outer.Inner();

in.display();

}

}

class Outer{

private int a = 5;

private static int b = 10;

public static void print() { System.out.println("print()"); }

public void show() { System.out.println("show()"); }

public Outer(){}

protected static class Inner{

private static int c = 15;

private int d = 20;

public Inner(){ System.out.println("성공"); }

public void display(){

System.out.println("d = " + d);  //a접근안됨(에러), b c d  됨

print();  //show() 접근안됨

}

}

}

//멤버는 static에게 접근 가능하다. static은 바깥쪽 멤버에 접근이 불가능하다. 주소를 사용해야 가능.

------------------

public class NestedClassDemo {

public static void main(String[] args) {

A.B.C.D d = new A.B.C.D();

}

}

class A{

static class B{

static class C{

static class D{

public D() { System.out.println("success"); }

}

}

}

}

//static 메소드를 만드는 목적은 주소없이 접근하기 위해서이다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

/*

 * Member Class

 * 1. 생성방법 : Outer class의 주소로 접근

 * 2. 사용목적 : 다중상속

 * 3. 제한사항 : static variable 과 static method를 소유할 수없다.

 */

public class MemberClassDemo {

public static void main(String[] args) {

Outer1 out = new Outer1();

Outer1.Inner1 in = out.new Inner1();

in.display();

}

}

class Outer1{

private int a = 5; //outer class's member variable

private static int b = 10;  //outer class's static variable

class Inner1{

private int c = 50;

private static int d = 100; //에러발생. 멤버클래스는 static 변수와 static 메소드를  가질 수 없다.

public Inner1(){ System.out.println("Success"); }

public void display(){

System.out.println("d = " + d);  //a,b,c 가능, d 에러발생.

}

}

}

--------------------

public class MemberClassDemo {

public static void main(String[] args) {

CC cc = new CC();

CC.DD dd = cc.new DD();

dd.display();

}

}

class AA{int a = 5;}

class BB{int b = 10;}

class CC extends AA{

int c = 100;

class DD extends BB{

int d = 5000;

public void display(){

System.out.printf("a = %d, b = %d, c = %d, d = %d\n", a,b,c,d);

}

}

}

출력:

a = 5, b = 10, c = 100, d = 5000

Member Inner Class는 스태틱만 안가지면 된다. 그럼 모든것을 다할 수 있다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

/*

 * Local Class

 * 1. 생성방법 : Inner class가 속해 있는 메소드가 호출돼야 한다.

 * 2. 사용목적 : 객체의 life cycle 을 짧게...

 * 3. 제한사항 : 1) access modifier 사용 불가능

 *   2) static 사용불가능

 *   3) local Inner class가 속해있는 메소드의 지역변수 접근 불가능.

 *   4) local inner class가 속해있는 메소드의 지역상수 접근 가능.

 */

public class LocalClassDemo {

public static void main(String[] args) {

Outer2 out = new Outer2();

out.display();

}

}

class Outer2{

private int a = 5;

private static int b = 10;

public void display(){ //Outer class's method

int c = 100;  //local variable -지역변수는 public, private 등을 못 붙인다. static 못붙인다. 

class Inner2{ // 따라서 지역클래스도 access modifier을 붙일 수 없다. static 못붙인다.

int d = 500;

public Inner2(){ System.out.println("Success"); }

public void print(){

System.out.println("d = " + d); //a,b,d 가능. c 에러발생. 지역클래스는 지역변수에 접근 불가능. d는 자기것이기 때문에 접근가능.

} //만약 c가 final int c 라면 접근 가능.

}

Inner2 in = new Inner2(); //메소드에서는 순서를 지켜줘야한다. class Inner2와 이것이 순서가 바뀌면 에러발생.

in.print();

}

}

//local class는 일반적으로 잘사용하지 않으나 이벤트에 사용.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

4. Anonymous Class

public class AnonymousClassDemo {

public static void main(String[] args) {

new AnonymousClassDemo().print();

}

void print(){

final int finalNum = 10;

/*Temp t = new Temp();

t.display();*/ //일반적으로 이와같이 시작하는 것이 아니라, 아래처럼

Temp t= new Temp(){  //지역클래스이기떄문에 private public 못붙인다. static 못붙인다.

@Override

public void display(){

System.out.println("재정의된 display()");

System.out.println("finalNum = " + finalNum);  //final 상수는 접근가능

}

}; //<-- 이 세미콜론은 지우면안된다. 지우면 에러발생.

t.display();

}

}

class Temp{

public void display(){

System.out.println("Called display()");

}

}

//local class와 제한사항이 거의 똑같지만 하나더 추가 된것이 세미콜론이다. 

출력:

재정의된 display()

finalNum = 10

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

enum

Class A, interface AA, enum AAA는 표현한 것이 같다

enum은 나열의 목적이지, 값의 저장이나 연산을 하진않는다.

Class A {

   public static final int SUN = 0;

   public static final int MON = 0;

}

interface AA{

   int SUN = 0, MON = 1;

}

enum AAA{

   SUN, MON;

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

값은 줄 수 있지만 생성자를 통해 줘야한다.

enum 내에서는 순서가있다.

생성자의 앞에 아무것도 붙이지 못한다.


public enum Weekend {

SUN(0), MON(5), TUE(100), WED(250), THU(500), FRI(1000), SAT(2000);  //값을 주려면 모두  다주어야한다.

private int value;

Weekend(int value){  //생성자 앞에 아무것도 붙이면 안된다.

this.value = value;

}

public int getValue() { return this.value; }

}



public class EnumDemo {

public static void main(String[] args) {

Weekend w = Weekend.WED;

//int su = (int)w; //자바에서는 enum에 들어있는 값들을 숫자로 바꿀 수없다.

System.out.println(w);

System.out.println(w.toString());

System.out.println(w.ordinal()); //c에서처럼 숫자로

Weekend [] array = Weekend.values();

for(int i = 0 ; i < array.length ; i++){

System.out.printf("%s(%d) --> %d\n", array[i].name(), array[i].getValue(),  array[i].ordinal());

}

}

}

//enum은 switch 를 사용하는데 유용. 데이터에대한 binary를 지정하고자할때 유용.

//enum은 switch 를 사용하는데 유용. 데이터에대한 binary를 지정하고자할때 유용.

출력:

WED

WED

3

SUN(0) --> 0

MON(5) --> 1

TUE(100) --> 2

WED(250) --> 3

THU(500) --> 4

FRI(1000) --> 5

SAT(2000) --> 6

Weekend [] array = Weekend.values();

for (Weekend we : array){

System.out.println(we.name() +"(" + we.getValue() + ") --> " +we.ordinal());

이렇게 써줘도 똑같이 값이 출력된다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Exception

exception 은 개발자입장에서 자기가 생각한 상황에서 벗어난 상황을 생각해서 처리하는 것.


import java.util.Scanner;

public class ExceptionDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int su, num;

System.out.print("첫번째 숫자 입력 :");

su = scan.nextInt();

System.out.print("두번째 숫자 입력(0은 안됨) :");

num = scan.nextInt(); //두번째 숫자가 0을 받으면 오류가 발생한다.

try{

System.out.printf("%d / %d = %d\n", su, num, (su/num));

}catch (ArithmeticException ex){

System.out.println("예외상황발생");

}

}

}

출력:

첫번째 숫자 입력 :3

두번째 숫자 입력 :0

예외상황발생

----------------------

checked exception :try, catch를 꼭 써야한다. 

unchecked exception : error와 runtimeException의 자식들은 꼭 써주지 않아도된다.

위 코드에서 사용자가 조심하면 try catch는 써주지 않아도된다.

checked exception은 try catch를 써주지 않으면 컴파일단계에서 에러가난다


import javax.swing.JOptionPane;

public class ExceptionDemo1 {

public static void main(String[] args) {

int kor = Integer.parseInt(JOptionPane.showInputDialog("국어점수를 입력하세요 : "));

System.out.printf("kor = %d\n", kor);

}

}

//여기서 예외상황은, 만약 점수를 aaa를 입력했다면??

//이 코드는 실행중에 오류를 발생시킬 수 있으므로 runtimeException이라고 한다.

//Integer/parseInt는 부모가 java.lang.RuntimeException이다.


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

가장많이 발생하는 exception


public class ExceptionDemo2 {

public static void main(String[] args) {

Test t = new Test();

t.su = 10;

System.out.println(t.su);

t = null;

System.out.println(t.su);

}

}

class Test{

int su;

}

출력:

10

Exception in thread "main" java.lang.NullPointerException

at ExceptionDemo2.main(ExceptionDemo2.java:8)

exception 중 널포인터익셉션이 80프로정도발생한다. 이 코드에서는 Test t를 널값을 넣어주었는데 t.su를 출력하려고 해서 나타난 에러.

널포인터익셉션 에러는 얻어오려는 값이 비어있을때 발생한다.

또 다른 경우를 보면

public class ExceptionDemo2 {

public static void main(String[] args) {

int su = -5;

int [] array = new int[su];

}

}

class Test{

int su;

}

이런 Exception in thread "main" java.lang.NegativeArraySizeException

at ExceptionDemo2.main(ExceptionDemo2.java:10)

에러가 발생한다.

여기서

try{

int [] array = new int[su];

}catch(NegativeArraySizeException ex){

System.out.println("예외상황발생");

}

이렇게 처리를 해주면 정상적으로 돌아갈 것이다. 하지만 catch부분을 

catch (ArithmeticException ex){

System.out.println("예외상황발생");

}

다른 예외상황을 써준다면 다시 오류가 발생할 것이다.

------

만약  아래코드에서 1번 줄에서 예외상황이 발생한다면 aaaaa는 출력하지 않고 catch로 간다.

try{

1번-> System.out.printf("%d / %d = %d\n", su, num, (su/num));

System.out.println("aaaaa");

}catch (ArithmeticException ex){

System.out.println("예외상황발생");

}

-----------------------

try{

System.out.printf("%d / %d = %d\n", su, num, (su/num));

}catch (ArithmeticException ex){

System.out.println("예외상황발생");

}catch (NullPointerException ex){

System.out.println("NullPointerException");

}catch(ArrayIndexOutOfBoundsException ex){

System.out.println("ArrayIndexOutOfBoundsException");

}

어떤 exception인지 몰라서 이렇게 써주는 것은 괜찮다. 하지만 만개의 exception이 있다면 모두 이렇게 써주기는 힘들것이다.

catch(Exception ex){

System.out.println("마지막 보루");

}

그래서 부모를 써주는 방법이 있다.

----------------------

만일 아래와 같이 써주면 Exception 의 아래에 있는 예외처리상황은 쓸데 없는 처리가 된다.

try{

System.out.printf("%d / %d = %d\n", su, num, (su/num));

}catch (Exeption ex){

System.out.println("예외상황발생");

}catch (NullPointerException ex){

System.out.println("NullPointerException");

}

그래서 위로 갈수록 자식(더좁은폭)으로 가야한다.

물론 

try{

System.out.printf("%d / %d = %d\n", su, num, (su/num));

}catch (Exeption ex){

System.out.println("예외상황발생");

}

이렇게만 써줘도 되긴하지만 그러면 어떤 예외상황인지 알수 없게 된다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Throwing Exceptions


public class ExceptionDemo3 {

public static void main(String[] args) {

ExceptionDemo3 ed = new ExceptionDemo3();

ed.a();

}

void a(){

b();

}

void b(){

c();

}

void c(){

d();

}

void d(){

System.out.println(5/0);

}

}

출력:

Exception in thread "main" java.lang.ArithmeticException: / by zero

at ExceptionDemo3.d(ExceptionDemo3.java:17)

at ExceptionDemo3.c(ExceptionDemo3.java:14)

at ExceptionDemo3.b(ExceptionDemo3.java:11)

at ExceptionDemo3.a(ExceptionDemo3.java:8)

at ExceptionDemo3.main(ExceptionDemo3.java:5)

경로상의 거치는 모든 메소드는 다걸린다. d()에서 해결 못하면 c()로 계속해서 넘겨준다.

그러면 d에서 발생한 에러지만 중간인 b 메소드를 try catch 처리 해주면

void b(){

try{

c();

}catch(Exception ex) {System.out.println("여기서 잡았음"); }

}

중간에 커트되어 더이상 오류가 발생하지 않는다.

이것이 exception의 장점이다. 전파되기 때문에 누구라도 중간에 잡아주기만 하면 더이상 에러가 발생하지 않는다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Exceptions에 대한 정보를 출력하는 방법


import javax.swing.JOptionPane;

import java.util.Scanner;

public class ExceptionDemo4 {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

ExceptionDemo4 ed = new ExceptionDemo4();

try{

ed.input(scan);

}catch (RuntimeException ex){

JOptionPane.showMessageDialog(null,ex.getMessage());

//System.out.println(ex); //1. ex.getMessage() : 사용자용 2. ex.toString

//3.ex.printStackTrace(); //일련의 과정을 추적해서 찍는.. 개발자용 

}

}

void input(Scanner scan) {

System.out.println("국어 점수 입력 : ");

int kor = scan.nextInt();

if(kor < 0 || kor > 100) 

throw new RuntimeException("국어 점수는 0부터 100점까지 입니다");

}

}

//이 코드는 범위에벗어나는 점수를 입력했을 때 "국어점수는 0부터 100점까지 입니다" 의 메세지를 띄어준다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Declaring Exceptions

위 소스에서 input을 

void input(Scanner scan) throws RuntimeException { //만드는 사람은 반드시 exception을 던지고 있는 것을 선언해준다. 가져다 쓰는 사람을 위해서. 

System.out.println("국어 점수 입력 : ");

int kor = scan.nextInt();

if(kor < 0 || kor > 100) 

throw new RuntimeException("국어 점수는 0부터 100점까지 입니다");

}

이렇게 써준다. 메소드 안에서는 throw, 밖에서는 throws 이다. 


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

import java.io.File;  //ctrl+shift+o

import java.io.FileNotFoundException;

import java.util.Scanner;


import javax.swing.JFileChooser;


public class ExceptionDemo5 {

public static void main(String[] args) throws FileNotFoundException { //input에서 던진 것을 여기서 ed.input을 try catch처리 해주거나 throws를 해주어야한다. 컴파일러에게 던진다.

ExceptionDemo5 ed = new ExceptionDemo5(); 

ed.input();

}

void input() throws FileNotFoundException{ //throws FileNotFoundException를 써주거나 try catch 처리를 해주어야 한다.

File file = null;

JFileChooser jc = new JFileChooser();

int result = jc.showOpenDialog(null);

if(result == JFileChooser.APPROVE_OPTION){ //열기버튼을 눌렀다면

file = jc.getSelectedFile();

}

Scanner scan = new Scanner(file);

for(int i = 0 ; i <12 ; i++){

System.out.println(scan.nextLine());

}

}

}

//showOpenDialog로 파일을 선택할 수 있게 창이 뜬다. 그래서 열려는 파일을 찾아서 선택한다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

finally - exception의 발생여부와 관계없이 무조건 실행된다.

위 코드를 throws FileNotFoundException을 써주지 말고 try catch처리를 해주자.


import java.io.File; 

import java.io.FileNotFoundException;

import java.util.Scanner;


import javax.swing.JFileChooser;


public class ExceptionDemo5 {

public static void main(String[] args) { 

ExceptionDemo5 ed = new ExceptionDemo5(); 

ed.input();

}

void input() { 

File file = null;

JFileChooser jc = new JFileChooser();

int result = jc.showOpenDialog(null);

if(result == JFileChooser.APPROVE_OPTION){ //열기버튼을 눌렀다면

file = jc.getSelectedFile();

}

Scanner scan = null;

try{

scan = new Scanner(file);

for(int i = 0 ; i <12 ; i++){

System.out.println(scan.nextLine());

}

}catch(FileNotFoundException ex){

System.out.println("File Not Found");

}finally{

System.out.println("항상처리");

scan.close();

}

}

}

순서는 try - catch - finally 가 정식이다. 그리고 try - catch 만 쓸 수 있다.

catch를 쓰지않고 throws FileNotFoundException 을 하고 try - finally 도 가능하다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Creating Your Own Exception - 필요하다면 내가 직접 exception을 만들 수 있다.

이것을 명심해야한다. 1. 생성자를 반드시 써야한다. 2. 부모가 누구냐를 따져야한다. 

runtime exception을 부모로한다면 unchecked exception이 될 것이고~~.


//unchecked exception

public class EnglishException extends RuntimeException{

public EnglishException (String msg){

super(msg); //나의 부모가 처리

}

}



//checked Exception

public class KoreanException extends Exception {

public KoreanException (String msg){

super(msg);

}

}



//국어는 checked, 영어는 unchecked

public class Student {

private int kor, eng;

public Student(int kor, int eng) throws KoreanException, EnglishException {

if(kor < 0 || kor > 100) throw new KoreanException("국어점수는 0부터 100점까지입니다.");

else this.kor = kor;

if(eng < 0 || eng > 100) throw new EnglishException("영어점수는 0부터 100점까지입니다.");

else this.eng = eng;

}

@Override

public String toString(){

return String.format("kor = %d,  eng = %d" , this.kor, this.eng);

}

}



import java.util.Scanner;

import javax.swing.JOptionPane;


public class ExceptionDemo6 {

public static void main(String[] args) {

ExceptionDemo6 ed = new ExceptionDemo6();

ed.input();

}

void input(){ 

int kor, eng;

Scanner scan = new Scanner(System.in);

System.out.print("국어점수 : "); kor = scan.nextInt();

System.out.print("영어점수 : "); eng = scan.nextInt();

Student chulsu = null;  //try를 써주지 않으면 KoreanException은 checked exception이기 떄문에 오류 발생.

try{

chulsu = new Student(kor, eng);

System.out.println(chulsu);

}catch(KoreanException ex){

JOptionPane.showMessageDialog(null, ex.getMessage());

}catch(EnglishException ex){

JOptionPane.showMessageDialog(null, ex.getMessage());

}catch(Exception ex){

JOptionPane.showMessageDialog(null, ex.getMessage());

}

}

}


StarUML

composition : 필수적인관계. 라이프 사이클이 같음. 베스킨라빈스의 아이스크림을 얼리는 냉장고는 필수적임. 오직아이스크림만을 팔기때문에.

association : 편의점에 아이스크림을 얼리는 냉장고. 아이스크림을 팔지않는다고해서 편의점이 아닌것은 아님.

dependency :

dependency의 stereotype : 파라미터로 받아오면 parameter. 새로 만들면 create.

멤버변수는 association, aggregation, composition 중 하나의 관계를 갖는다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class Account {

private String name;

private int balance;

public Account(String name, int balance) {

this.name = name;

this.balance = balance;

}

@Override

public String toString(){

return String.format("%s(%d)", this.getName(), this.getBalance());

}

public void deposite(int money){ 

this.balance += money;

}

public boolean withdraw(int money){

if(this.balance >= money){

this.balance -= money;

return true;

}else{

return false;

}

}

public int getBalance() { return this.balance; }

public String getName() {

return name;

}

}



import java.util.Scanner;

public class AccountTest {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

Account chulsu = new Account("김철수", 0);

int choice = 0;

do{

System.out.print(chulsu + " : 1)출금, 2)입금, 3)종료 : ");

choice = scan.nextInt();

switch(choice){

case 1: withdraw(chulsu, scan); break;

case 2: deposite(chulsu, scan); break;

case 3 : break;

}

}while(choice == 1 || choice ==2);

}

static void withdraw(Account a, Scanner scan){

System.out.print("How much ? ");

int money = scan.nextInt();

if(a.withdraw(money)) System.out.println("출금 성공");

else System.out.println("잔액이 부족합니다");

}

static void deposite(Account a, Scanner scan){

System.out.print("How much ? ");

int money = scan.nextInt();

a.deposite(money);

}

}

출력:

김철수(0) : 1)출금, 2)입금, 3)종료 : 2

How much ? 5000

김철수(5000) : 1)출금, 2)입금, 3)종료 : 2

How much ? 3000

김철수(8000) : 1)출금, 2)입금, 3)종료 : 1

How much ? 7000

출금 성공

김철수(1000) : 1)출금, 2)입금, 3)종료 : 1

How much ? 3000

잔액이 부족합니다

김철수(1000) : 1)출금, 2)입금, 3)종료 : 3

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

다형성관계에서 오버라이딩(부모주소로 자식의 오버라이드 된 메소드를 쓰면 다형성, 자식주소로 부모 것을 쓰면 상속)

public class Bumo {

public void display(){

System.out.println("나는 부모의 display 메소드");

}

public void print() {

System.out.println("나는 부모의 print 메소드");

}

}


public class Jasik extends Bumo {

@Override

public void display(){

System.out.println("나는 자식의 display 메소드");

}

public void show(){

System.out.println("나는 자식의 show 메소드");

}

}



public class PholymorphismDemo1 {

public static void main(String[] args) {

Bumo b; //선언, compile type

b = new Jasik(); //할당, runtime type

b.print();  //부모형은 당근 자기 메소드에 접근 가능.

b.display(); //부모형은 자식형의 재정의된 메소드에 접근 가능.

// b.show(); //에러. 부모에게 show의 메소드가 없기 때문에 에러 발생. 부모형은 자식형의 새로운 메소드 접근 불가.

if(b instanceof Jasik){

Jasik ja = (Jasik)b;

ja.print(); //자식형은 부모의 메소드에 접근 가능

ja.display(); //자식형은 재정의된 자기의 메소드에 접근가능

ja.show(); //자식형은 당근 자기만이 만든 메소드에 접근가능

}else{

System.out.println("안됨");

}

}

}


출력:

나는 부모의 print 메소드

나는 자식의 display 메소드

나는 부모의 print 메소드

나는 자식의 display 메소드

나는 자식의 show 메소드


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ심화ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Account class는 위의 소스를 사용하고, 


public class TimeAccount extends Account{

private int timebalance;


public TimeAccount(String name, int balance, int timebalance) {

super(name, balance);

this.timebalance = timebalance;

}

@Override

public String toString(){ //자기부모의 Account를 오버라이딩

return String.format(super.toString() + "[%d]", this.getTimebalance());

}

public int getTimebalance() {

return timebalance;

}


public void setTimebalance(int timebalance) {

this.timebalance = timebalance;

}

}



public class PholymorphismDemo {

public static void main(String[] args) {

/* Account a;

Account chulsu = new Account("김철수", 0);

TimeAccount younghee = new TimeAccount("이영희",100, 5000);

 

a = chulsu;  //가능

System.out.println(a);

a = younghee;  //가능

System.out.println(a);*/

TimeAccount ta;

TimeAccount chulsu = new TimeAccount("김철수",100,50000);

Account younghee = new Account("이영희", 2000);

/*ta = chulsu;

System.out.println(ta);

*/

//ta = younghee; //에러. 부모는 자식으로 자동형변환이 되지않는다.

//ta = (TimeAccount)younghee; //강제형변환은 가능하지만, instanceof로 확인해봐야 알 수 있다. 여기서는 강제형변환이 되지않는다.

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Polymorphic Parameters

public class Car {

private String name;

public Car(String name){

this.name = name;

}

public String getName() {

return name;

}

}


public class Sonata extends Car {

public Sonata(String name){

super(name);

}

}


public class Matiz extends Car {

public Matiz(String name){

super(name);

}

}


public class Canival extends Car {

public Canival(String name){

super(name);

}

}


public class CarCenter {

public static void main(String[] args) {

CarCenter cc = new CarCenter();

Sonata so = new Sonata("소나타");

Matiz m = new Matiz("마티즈");

cc.repair(so);

cc.repair(m);

cc.repair(new Canival("카니발"));

}

void repair(Car car){ //instanceof는 형변환이 가능한지 뿐만 아니라, 원형을 알아낼 때도 쓰인다.

if(car instanceof Sonata){

System.out.println("현대 소나타가가 잘 수리됐습니다");

}else if(car instanceof Matiz){

System.out.println("쉐보레 마티즈가 잘 수리됐습니다");

}else if(car instanceof Canival){

System.out.println("기아 카니발이 잘 수리됐습니다");

}

//System.out.println(car.getName() + "가 수리됐습니다");

}

}

출력:

현대 소나타가가 잘 수리됐습니다

쉐보레 마티즈가 잘 수리됐습니다

기아 카니발이 잘 수리됐습니다

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ


public class PholymorphismDemo2 {

public static void main(String[] args) {

//일반적으로 Sonata배열이면 모든 배열이 Sonata형.

/*Sonata [] array = new Sonata[2];

array[0] = new Sonata("소나타1");

array[1] = new Sonata("소나타2");*/

//하지만 Heterogeneous Collections 은 다른종류의 타입들로 이루어진 배열??

Car [] array = new Car[3];

array[0] = new Sonata("소나타");

array[1] = new Canival("카니발");

array[2] = new Matiz("마티즈");

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

오버라이딩된 자식의 메소드는 부모의 메소드 보다 더 넓거나 같게 받아들일 수 있어야한다....(??)

부모가 public 이면 자식은 더 넓거나 같아야 하기에 public만 가능하다.

부모가 protedcted이면 자식은 protected, public이 가능하다.

부모가 default면 자식은 default, protected, public이 가능하다.



public class OverrideDemo {

public static void main(String[] args) {

//Base b = new Derived(); b.display();  //다형성. 

//Base b = new Base();  b.display();

Derived d = new Derived(); d.display(); //만약 Derived에 display메소드가 없으면 부모에서 찾는다.

}

}

class Base{

void display(){ System.out.println("나는 부모의 메소드"); }

}

class Derived extends Base{

protected void display(){ System.out.println("나는 자식의 메소드"); } //오버라이딩된 자식의 display가 부모의 display보다 넓거나 같음을 만족한다.

}

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

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

추상 메소드 : 오버라이딩의 강제화

추상 클래스 : 다형성의 강제화


추상메소드

public class AbstractMethodDemo {

public static void main(String[] args) {

자식 자 = new 자식();

자.display();

}

}

abstract class 부모 {

public abstract void display();

public void print(){}

}

class 자식 extends 부모{

public void display(){

System.out.println("나는 추상메소드");

}

}

출력:

나는 추상메소드

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Interface

//1. interface에는 public static final이 생략된 상수만 넣는다.

//2. interface에는 public abstract 이 생략된 추상메소드만 넣는다.

public interface Datable {

int SUN = 0, MON = 1, TUE = 2, WED = 3, THU = 4, FRI = 5, SAT = 6; //interface는 변수를 넣을 수없다. 오직 상수값 만을 가짐(final 생략). 그리고 private을 넣을 수 없음.

void set(int date);

int get();

}


//3. class가 interface로 부터 상속을 받을 때는 implements를 사용한다.

//4. interface의 자식 class는 반드시 모든 메소드를 재정의하거나, 추상클래스가 되어야한다.

//5. 자식 calss에서 interface 속의 메소드를 재정의할 때 반드시 public 이어야 한다.

public class Date implements Datable {

private int date; //member variable

@Override

public void set(int date) {

this.date = date;

}


@Override

public int get() {

return this.date;

}


}


//6. interface는 instance가 될 수 없다.

public class InterfaceDemo1 {

public static void main(String[] args) {

//Datable d = new Datable();

Datable d = new Date();

d.set(Datable.WED);

System.out.println(d.get());

}

}

출력 :

3

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

interface의 모든 메서드는  abstract. 모든 variable은 constant. 오버라이딩 메소드는 public이 생략되어있다.

new를 못쓰고 polymorphism을 써서 초기화할수 있다.

public interface XYZ {

void xyz();

}


public interface YZW {

void yzw();

}

//7. Interface 끼리의 상속은 extends를 사용하며 다중상속이 가능하다.

public interface ABC extends XYZ, YZW {

int SU = 100;

void abc();

}


public interface DEF {

int SU = 50000;

void def();

}


public class InterfaceDemo2 implements ABC, DEF { //XYZ와 YZW는 ABC가 상속받았으므로 안써주어도된다.

public void abc(){System.out.println("Called abc()"); }

public void def(){System.out.println("Called def()"); }

public void xyz(){System.out.println("Called xyz()"); }

public void yzw(){System.out.println("Called yzw()"); }

public static void main(String[] args) {

//XYZ xyz = new InterfaceDemo2();  //다형성 구현해야. 아래처럼 써줄수도있고 이것처럼 써줘도 된다.

XYZ xyz;

InterfaceDemo2 id = new InterfaceDemo2();

xyz = id; xyz.xyz();

//xyz.abc(); //에러. 재정의된 메소드만 가능하다.

YZW yzw = new InterfaceDemo2(); yzw.yzw();

ABC [] array = new ABC[3]; //ABC자식을 위한 배열이지, ABC 배열을 만들려는 것이 아니기 떄문에 만들어진다(ABC자체의 new는 못하지만)

array[0] = id;

array[1] = new InterfaceDemo2();

array[1].abc();

System.out.println("ABC's SU = " + array[1].SU);

System.out.println("DEF's SU = " + DEF.SU);

}

}

출력:

Called xyz()

Called yzw()

Called abc()

ABC's SU = 100

DEF's SU = 50000

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

StarUML : class->abstract 는 generalization

class->interface 는 realization

동그란 interface와 네모난 interface를 만들 수 있다.(네모난 interface는 stereotype에 abstract 써주는 방식)

interface의 모양은 멤버가있으면 네모, 없으면 동그라미로 만든다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Clone(복제)


public class InterfaceDemo3 {

public static void main(String[] args) {

Point original = new Point(100, 200);

/*Point another = original.copy(); //주소복사

System.out.println(another);

original.set(5000,  10000);

System.out.println(another);*/

Point another = original.myClone();

System.out.println(another);

original.set(5000,10000);

System.out.println(another);

}

}

//flag interface, mark interface

class Point extends Object implements Cloneable{ //implements Cloneable을 붙여줌으로 써 복제가 가능함을 말해준다.

private int x, y;

public Point(int x, int y) { this.x = x; this.y = y; }

public Point copy(){ //주소복사

return this;

}

public Point myClone(){

Object obj = null; //clone은 리턴타입이 object라 하나 만들어줌.

try{

obj = this.clone();

}catch(CloneNotSupportedException ex){

System.out.println("복제실패");

}

return (Point)obj;

}

public void set(int x, int y) { this.x = x; this.y = y;}

@Override

public String toString(){

return String.format("(x,y) = (%d, %d)", this.x, this.y);

}

}

출력:

(x,y) = (100, 200)

(x,y) = (100, 200)

주소복사를 하면 원본값이 바뀌었을때  같이 바뀌었으나, 

복제는 원본값이 바뀌어도 값이 바뀌지 않았다. 복제는 똑같은 것이 하나 더 생겨난것이기 때문.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

흩어진 java파일들을 컴파일해서 실행하는 방법...?

1. Class Path 세팅. & 2. Package사용. 3.jar 사용


Insa.java

package com.java_oracle.libs.HR;


public class Insa {

public String name = "Duncan";

}



Money.java

package com.java_oracle.libs.finance;

public class Money {

public double balance = 10_000_000;

}



ClassDemo.java

public class ClassPathDemo {

public static void main(String[] args) {

Insa in = new Insa();

Money m = new Money();

System.out.println("name = " + in.name);

System.out.println("balance = " + m.balance);

}

}


1. classpath 설정.

원본에 접근하려는 폴더가 다른 곳에 있으면 컴파일할 때

javac -classpath C:\temp ClassPathDemo.java 

    접근하려는 폴더 위치  main이름

실행할때는 java -cp .;C:\Temp ClassPathDemo

         -classpath  접근하려는 폴더위치(윈도우의 경우에는 ; , 리눅스는 :)

자바홈에 없거나 현재폴더에 없으면 classpath를 사용한다.

이러한 방법이 귀찮기 때문에 시스템의 환경변수 설정창에가서 System variable에서 New를 눌러주고 Variable name에는 CLASSPATH, Variable value에는 .;C:Temp 를 등록해준다.

등록한 후 재부팅 or set 과정을 해줌. 도스창을 닫고(기존의 정보를 갖고있기 때문에) 다시 켜줌. 

set classpath 엔터. echo%classpath%로 확인.

이러한 작업을 해주면 class파일의 위치가 서로 다른 곳에 있어도, 다른 명령어없이 javac ClassPathDemo.java로 컴파일 가능하고, java ClassPathDemo 로 실행까지 가능하다.


2. 패키지를 사용.

패키지를 package com.java_oracle.libs.HR; 이런식으로 써준다면 

               --------------------------- 이러한 경로는 컴파일할 때 쓴곳에 만들어지는 것이다. 

javac -d D:\JavaRoom Insa.java 를 한다면  D드라이브의 JavaRoom이라는 폴더에 com/java_oracle/libs/HR 이라는 폴더에 insa.class가 생긴다.

이렇게 만들어진 것은 또 컴파일할 때 에러가 생긴다. 왜냐하면 classpath에도 없고 com.java_oracle.libs.HR의 위치에 있기 때문이다.

그래서 해주는 것이 메인에서 import를 써주는 것이다.

//import com.java_oracle.libs.HR.*;  //1번째 방법

import com.java_oracle.libs.HR.Insa; //2번째 방법

ImportDemo.java

public class ImportDemo {

public static void main(String[] args) {

Insa in = new Insa();

//com.java_oracle.libs.HR.Insa in = new com.java_oracle.libs.HR.Insa(); //3번째 방법

Money m = new Money();

System.out.println("name = " + in.name);

System.out.println("balance = " + m.balance);

}

}



3.  jar 파일 만든다.

jar cvf mylib.jar com/    -com 폴더 밑의 전부를 mylib.jar 로 압축. com폴더는 위에서 패키지로 해준...

C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext 폴더에 mylib.jar 을 넣어준다.   -확장라이브러리는 무조건 ext폴더에~


import com.java_oracle.libs.finance.Money;

public class ImportDemo1{

public static void main(String[] args) {

com.java_oracle.libs.HR.Insa in = new com.java_oracle.libs.HR.Insa();

Money m = new Money();

System.out.println("name = " + in.name);

System.out.println("balance = " + m.balance);

}

}


classpath를 찾고 현재폴더를 찾고 다 찾아도 파일을 못찾는다. 그러면 컴파일러는 ext폴더를 찾는다. 그곳에서 mylib.jar를 찾아서 컴파일이 가능하게한다.

이클립스를 실행시키면 자바프로젝트를 만들어주면, JRE System Library에 mylib.jar가 있는 것을 볼 수 있다. 

이것은 이클립스의 단점인데 새로운 자바프로젝트를 만들면 계속해서 mylib.jar가 사용하지 않을것인데도 계속해서 있을 것이다.

ext폴더에서 mylib.jar을 지우게되면 import com.java_oracle.libs.finance.Money; 이런식으로 사용은불가하다. 

사용을 위해서 프로젝트를 우측버튼을 눌러 build path 에서 configure build path를 눌러준다. 

Libraries 탭을 눌러서 Add External JARs를 눌러주고 mylib.jar를 찾아서 선택해준다. (또는 우측버튼에서 buildpath-add external archive 눌러서 mylib.jar를 선택해주어도된다.

그리고 다시 import를 사용해보면 되는 것을 볼 수 있다.



import java.util.Calendar; //오늘날짜를 출력하기 위해서


public class Date {

private int year, month, day;

public Date(){ //Default Constructor

Calendar now = Calendar.getInstance();

this.year = now.get(Calendar.YEAR);

this.month = now.get(Calendar.MONTH) +1;

this.day = now.get(Calendar.DATE);

}//기본생성자를 쓰는 것만으로도 오늘의 날짜를 알게.

@Override

public String toString(){ //그냥 출력을 하게되면 Date@1975d24 이런식으로 toStrig을 호출한다. 그래서 toString을 오버라이딩하는 작업.

return "Today is " + this.year + "년 " + this.month + "월 " + this.day + " 일...";

}

public int getYear() {

return year;

}


public void setYear(int year) {

this.year = year;

}


public int getMonth() {

return month;

}


public void setMonth(int month) {

this.month = month;

}


public int getDay() {

return day;

}


public void setDay(int day) {

this.day = day;

}

}



public class EncapDemo {

public static void main(String[] args) {

Date today = new Date();

//Date worldcup = new Date(2014,6,15); //아직 생성자를 이렇게 만들어주지않아 사용불가

System.out.println(today);  //today.toString을 호출한다.

}

}

출력:

Today is 2014년 3월 18 일...


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

/*

 * 1. this. --> 나의 -->나의 멤버변수, 나의 멤버메소드를 명시적으로 지칭할 때 사용

 * 2. this --> 나 --> 나전체를 파라미터나 리턴할 때 사용

 * 3. this() --> 나의 생성자가 나의 또 다른 생성자를 호출할 때 사용

 * 1) 반드시 생성자 메소드에서만 사용한다.

 * 2) 반드시 생성자 메소드 속에서 첫번째 줄에 사용해야 한다.

 */

public class ThisDemo {

public static void main(String[] args) {

Demo d = new Demo(); System.out.println(d);

Demo d1 = new Demo("Sally"); System.out.println(d1);

Demo d2 = new Demo(25); System.out.println(d2);

Demo d3 = new Demo("Michael", 40); System.out.println(d3);

}

}

class Demo{

private String name;

private int age;

public Demo(){

//new Demo("unknown" , 20); //new를 위에서 쓰고 또 new 를 쓰면 주소가 바뀐다.

this("unknown", 20);

}

public Demo(String name){

//new Demo(name, 20);

this(name, 20);

}

public Demo(int age){

//new Demo("unknown", age);

this("unknown", age);

}

public Demo(String name, int age){

this.name = name;

this.age = age;

}

@Override

public String toString(){

return "name = " + name + ", age = " + age;

}

}

출력:

name = unknown, age = 20

name = Sally, age = 20

name = unknown, age = 25

name = Michael, age = 40

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Instance Initialization Block


public class Car {

private String maker;

private String name;

private int price;

private final double PI;

{//초기화블록은 변경이 불가하고, 처음 한번만 호출되고, 다음부터는 호출이 불가능하다.

System.out.println("나는 초기화 블록");

this.maker = "Kia";

this.name = "K5";

this.price = 20_000_000;

this.PI = 3.14; //처음에 값을 정하고 바뀌지 않는 것이면 초기화블록에 넣어줘도 괜찮다.

}//생성자보다 먼저 메모리에 올라온다.

public Car(String maker, String name, int price) {

System.out.println("나는 생성자 메소드");

this.maker = maker;

this.name = name;

this.price = price;

}

@Override

public String toString(){

return "maker = " + this.maker + ", name = " + this.name + ", price = " + this.price;

}

}


public class ConstructorDemo {

public static void main(String[] args) {

Car car = new Car("현대", "Sonata", 20000000);

//Car car = new Car();

System.out.println(car);

}

}

출력:

나는 초기화 블록

나는 생성자 메소드

maker = 현대, name = Sonata, price = 20000000

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

상속(Inheritance) :starUML에서 Generallization : 직선화살표에 속이 빈 삼각형 모양

class TwoD{

int x,y;

public void display(){

System.out.printf("(x,y) = (%d, %d)\n", x, y);

}

}

class ThreeD extends TwoD{

int z;

public void print(){

System.out.printf("(x,y,z) = (%d, %d, %d)\n", x,y,z);

}

}

public class SangsokDemo {

public static void main(String[] args) {

ThreeD td = new ThreeD(); 

td.print();

}

}

출력:

(x,y,z) = (0, 0, 0)

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

private은 상속되지않는다

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

static은 상속과 관련이없다.

overshhadow, override 메소드는 상속되지않는다.


public class Point {  //모든객체는 오브젝트의 자식. extends Object가 생략되어 있음.

private int x, y;

public Point(){//만약 부모클래스의 기본생성자가 없으면 자식클래스에서 오류발생. 부모가 기본생성자를 만들어주던지, super를 써서 처리해주던지.. 

System.out.println("부모의 기본생성자");

}

public Point(int x){

this.x = x;

System.out.println("나는 부모 생성자");

}

public void display(int num){

System.out.println("나는 부모의 메소드");

}

}


public class SubPoint extends Point{

private int num;

public static void main(String[] args) {

SubPoint sp = new SubPoint();

//System.out.println(sp.x);

}

public SubPoint(){ //자식은 항상 부모의 기본생성자만 호출한다.

//super(5);

this.num = num;

System.out.println("나는 자식생성자");

}

public SubPoint(int num, int x){

//this(num);

super(x); //this나 super는 가장 먼저 써줘야한다. this를 주석처리하고 아래와 같이 써줌으로써 오류를 피한다.

this.num = num;

}

출력:

부모의 기본생성자

나는 자식생성자

-----------------------------------------------

public class Box {

private int width;

private int height;

private int depth;

public Box(int width, int height, int depth) {

this.width = width;

this.height = height;

this.depth = depth;

}

public void display(){

System.out.printf("width = %d, height = %d, depth = %d\n", width, height, depth);

}


}



public class BoxWeight extends Box{

private int weight;

public BoxWeight(int width, int height, int depth, int weight){

super(width, height, depth);

this.weight = weight;

}

public void displayWeight(){

System.out.printf("wieght = %d\n", weight);

}

}



public class ShippedBox extends BoxWeight {

private int shippingprice;

public ShippedBox(int width, int height, int depth, int weight, int shippingprice){

super(width, height, depth, weight);

this.shippingprice = shippingprice;

}

public void displayShipprice(){

System.out.printf("shippingprice = %d\n", shippingprice);

}

}



public class SangsokDemo1 {

public static void main(String[] args) {

ShippedBox sb = new ShippedBox(10,20,30,40,500);

sb.display(); //Box

sb.displayWeight(); //BoxWeight

sb.displayShipprice();

}

}

출력 :

width = 10, height = 20, depth = 30

wieght = 40

shippingprice = 500

----------------------------------------------------

public class Bumo {

static int num;  //static variable

int su; //member variable

}



public class Jasik extends Bumo{

public void display(){

System.out.println("num = " + num + ",su = " + su);

}

}




public class SangsokDemo2 {

public static void main(String[] args) {

Jasik ja = new Jasik();

ja.display();

ja.su = 100;  //Jasik주소로 접근.

Bumo.num = 1000; //static은 자식필요없이 부모에게 직접 접근을할 수 있다. 이것은 상속이아니다.

ja.display();

}

}

출력:

num = 0,su = 0

num = 1000,su = 100

---------------------------------------------------

public class SangsokDemo3 {

public static void main(String[] args) {

Lion king = new Lion();

System.out.println("age = " + king.age);

king.display();

}

}


class Mammal{

int age = 50; //자식과 이름이 같으면 상속되지 않는다.

public void display(){ System.out.println("나는 부모의 메소드"); } //override메소드는 상속되지 않는다.

}

class Lion extends Mammal{

String age = "25"; //overshadow variable - 부모와 변수의 이름이 같음.

public void display(){ System.out.println("나는 자식의 메소드"); }  //메소드는 리턴타입 변수이름 

}

출력:

age = 25

나는 자식의 메소드

----------------------- overshadow 해결

public class SangsokDemo3 {

public static void main(String[] args) {

Lion king = new Lion();

// System.out.println("age = " + king.age);

king.print();

}

}


class Mammal{

int age = 50; //자식과 이름이 같으면 상속되지 않는다.

public void display(){ System.out.println("나는 부모의 메소드"); } //override 메소드는 상속되지 않는다.

}

class Lion extends Mammal{

String age = "25"; //overshadow variable - 부모와 변수의 이름이 같음.

public void print(){

System.out.println("this.age = " + this.age);

System.out.println("super.age = " + super.age);

}

public void display(){ System.out.println("나는 자식의 메소드"); }  //메소드는 리턴타입 변수이름 

}

출력:

this.age = 25

super.age = 50

-------------------------override 해결

public class SangsokDemo3 {

public static void main(String[] args) {

Lion king = new Lion();

// System.out.println("age = " + king.age);

king.print();

}

}


class Mammal{

int age = 50; //자식과 이름이 같으면 상속되지 않는다.

public void display(){ System.out.println("나는 부모의 메소드"); } //override 메소드는 상속되지 않는다.

}

class Lion extends Mammal{

String age = "25"; //overshadow variable - 부모와 변수의 이름이 같음.

public void print(){

//System.out.println("this.age = " + this.age);

//System.out.println("super.age = " + super.age);

super.display();

this.display();

}

public void display(){ System.out.println("나는 자식의 메소드"); }  //메소드는 리턴타입 변수이름 

}

출력:

나는 부모의 메소드

나는 자식의 메소드

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class OverrideDemo extends Object{

private int age;

public OverrideDemo(int age){ this.age = age;}

public static void main(String[] args) {

OverrideDemo od = new OverrideDemo(25);

System.out.println(od);

System.out.println(od.toString());

}

@Override

public String toString(){ //

//return "age = " + age; 아래처럼 쓴 것과 값이 같다.

return String.format("age = %d",  this.age);

}

}

출력:

age = 25

age = 25


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

/*

 * 비교

 * 1. Premitive type

 *  1) == 연산자만 사용

 *  2)값비교

 * 2. Reference type

 *  1) ==연산자, equals() 메소드

 *  2) 주소비교만한다.

 * 3. String type

 *  1) 값비교 : equals()

 *  2) 주소비교 : ==연산자

 */

public class EqualsDemo {

public static void main(String[] args) {

Test t = new Test(); t.num = 100;

Test t1 = new Test(); t1.num = 100;

if(t.num == t1.num) System.out.println("같다"); //if(t.equals(t1)) 절대주소 비교. t==t1과 같음.

else System.out.println("다르다");

}

}

class Test{

int num;

}

-----------------------string type 비교

public class EqualsDemo {

public static void main(String[] args) {

String str = "Hello";

String str1 = "Hello"; //두개의 값이 같으면 기존번지를 활용한다.

if(str == str1) System.out.println("같다"); //if(str.equals(str1)) 로 써도 출력은 같다.

else System.out.println("다르다");

}

}

class Test{

int num;

}

출력:

같다

-------------------

public class EqualsDemo {

public static void main(String[] args) {

String str = new String("Hello");  

String str1 = new String("Hello"); 

if(str == str1) System.out.println("같다"); //if(str.equals(str1))로하면 출력은 같다로 나온다.

else System.out.println("다르다");

}

}

class Test{

int num;

}

출력:

다르다

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

//equals() 메소드의 재정의

public class OverrideDemo1 {

public static void main(String[] args) {

Point p = new Point(100, 200);

Point p1 = new Point(100,200); //각각의 x와 y가 같은 지 비교하기위해 equals를 재정의

if(p.equals(p1)) System.out.println("같다");

else System.out.println("다르다");

}

}



public class Point {  //모든객체는 오브젝트의 자식. extends Object가 생략되어 있음.

private int x,y;

public Point(int x, int y){

this.x = x;

this.y = y;

}

@Override

public String toString(){

return String.format("(x,y) = (%d,%d)" , this.x, this.y);

}

@Override

public boolean equals(Object obj){

Point copy = (Point)obj;

if(this.x == copy.x && this.y == copy.y)return true;

else return false;

}

}

출력:

같다

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

다형성(Polymorphism)

/*

 * Casting (Conversion)

 * 1. Primitive type

 *  1) cast() 연산자

 *  2) implicit conversion, 암묵적, 자동형변환 : 작은 사이즈 --> 큰 사이즈

 *   4 + 89.5 --> 4.0 + 89.5 --.> double

 *   123 + "Hello" --> "123Hello"

 *  3) explicit conversion, 명시적, 강제적 형변환, demotion : 큰사이즈 --> 작은사이즈

 *   89.5 --> (int)89.5 

 * 2. Reference type

 *  1) 부모 자식 간 관계일 때

 *  2) 자식 --> 부모 : 강제적, 자동적 모두 가능

 *  3) 부모 --> 자식 : 강제적 형변환만 가능하고, 런타임때 instanceof 연산자로 체크해야한다(컴파일은되고 런타임때는 안될 수 있다.)

 */

public class ObjectCastingDemo {

public static void main(String[] args) {

Tico t = new Tico();

Sonata so = new Sonata();

//t = (Tico)so; //상속관계가 되어야 가능.

//t = so; //자식은 부모로 자동형변환이 된다.

if(t instanceof Sonata) so = (Sonata)t;  //부모--> 자식의 형변환이 되는지 확인하는 instanceof

else System.out.println("안됨");

so = (Sonata)t;  

}

}

class Tico{}

class Sonata extends Tico{}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class Point {  

private int x,y;

public Point(int x, int y){

this.x = x;

this.y = y;

}

@Override

public String toString(){

return String.format("(x,y) = (%d,%d)" , this.x, this.y);

}

@Override

public boolean equals(Object obj){

Point copy = (Point)obj;

if(this.x == copy.x && this.y == copy.y)return true;

else return false;

}

}


public class ObjectCastDemo1 {

public static void main(String[] args) {

ObjectCastDemo1 ocd = new ObjectCastDemo1();

Point p = new Point(100,200);

ocd.print(3,89.5,false,'A', "Hello", p);

}

void print(Object ... array){

for(Object obj : array){

if(obj.getClass().getName().equals("Point")){ //Point 클래스라면

if(obj instanceof Point) System.out.println("가능");

else System.out.println("불가능");

}else{ //Point class 가 아니면

System.out.println(obj);  //obj.toString()

}

}

}

}

출력:

3

89.5

false

A

Hello

가능

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class Dog extends Mammal {

@Override

public void saySomething(){

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

}



public class Cat extends Mammal {

@Override

public void saySomething(){

System.out.println("야옹야옹");

}

}



public class Korean extends Mammal {

@Override

public void saySomething(){

System.out.println("안녕하세요.");

}

}



public class American extends Mammal {

@Override

public void saySomething(){

System.out.println("Good Morning");

}

}



public class Mammal {

public void saySomething(){

System.out.println("그냥 운다");

}

}



import java.util.Scanner;

public class PholymorphismDemo {

public static void main(String[] args) {

PholymorphismDemo pd = new PholymorphismDemo();

int choice = 0;

do{

pd.showMenu();

choice = pd.input();

pd.output(choice);

}while(choice != 5 && choice >= 1 && choice < 5);

}

void showMenu(){

System.out.println("****Menu****");

System.out.println("1.Dog");

System.out.println("2.Cat");

System.out.println("3.Korean");

System.out.println("4.American");

System.out.println("5.Exit");

}

int input(){

Scanner scan = new Scanner(System.in);

System.out.println("당신은 어느 종족이십니까?");

int choice = scan.nextInt();

return choice;

}

void output(int choice){

Mammal m = null;

switch(choice){

case 1 : m = new Dog(); break;

case 2 : m = new Cat(); break;

case 3 : m = new Korean(); break;

case 4 : m = new American(); break;

}

m.saySomething();

}

}

출력:

****Menu****

1.Dog

2.Cat

3.Korean

4.American

5.Exit

당신은 어느 종족이십니까?

4

Good Morning

****Menu****

1.Dog

2.Cat

3.Korean

4.American

5.Exit

당신은 어느 종족이십니까?

1

멍멍멍멍

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class Box {

int width; //member variable

int height;

int depth;

}


public class EncapDemo {

public static void main(String[] args) {

Box box; //Box datatype dclaration

box = new Box(); //assignment

box.width = 10;

box.height = 5;

box.depth = 3;

System.out.println("박스의 부피는 " + box.width * box.height * box.depth);

Box box1 = new Box();

box1.width = 20;

box1.height = 40;

box1.depth = 10;

System.out.println("박스의 부피는 " + box1.width * box1.height * box1.depth);

}

}

출력:

박스의 부피는 150

박스의 부피는 8000


------------------Box 버전 업

public class Box1 {

int width;

int height;

int depth;

void getVolumn(){

System.out.println("박스의 부피는 " + width * height * depth);

}

}


public class EncapDemo2 {

public static void main(String[] args) {

Box1 box = new Box1();

box.width = 10;

box.height = 5;

box.depth = 3;

box.getVolumn();

}

}


----------------Box 버전 업

public class Box2 {

int width;

int height;

int depth;

int getVolumn(){

return width * height * depth;

}

}


public class EncapDemo2 {

public static void main(String[] args) {

Box2 box = new Box2();

box.width = 10;

box.height = 20;

box.depth = 5;

int result = box.getVolumn();

System.out.println("box의 부피는 " + result);

Box2 box1 = new Box2();

box1.width = 20;

box1.height = 50;

box1.depth = 10;

result = box1.getVolumn();

System.out.println("box1의 부피는 " + result);

}

}

출력:

box의 부피는 1000

box1의 부피는 10000


---------------Box 버전 업

public class Box3 {

int width;

int height;

int depth;

void setVolumn(int w, int h, int d){

width = w;

height = h;

depth = d;

}

int getVolumn(){

return width * height * depth;

}

}


public class EncapDemo3 {

public static void main(String[] args) {

Box3 box = new Box3();

box.setVolumn(10, 20, 5);

int result = box.getVolumn();

System.out.println("박스의 부피는 " + result);

Box3 box1 = new Box3();

box.setVolumn(20, 50, 10);

result = box.getVolumn();

System.out.println("박스1의 부피는 " + result);

}

}


-------------Box 캡슐화 적용

public class Box4 {

private int width;

private int height;

private int depth;

public void setVolume(int w, int h, int d){

width = w; height = h; depth = d;

}

public int getVolume(){

return width * height * depth;

}

}


public class EncapDemo4 {

public static void main(String[] args) {

Box4 box = new Box4();

//box.width = 30; //직접적으로 접근할 수 없다.

box.setVolume(10, 20, 30);

int result = box.getVolume();

System.out.println("부피는 " + result);

}

}


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

this 의 사용

/*

 * this 용법

 * 1. this.  --> 나의 --> 객체의 멤버변수 객체의 멤버 메소드를 명시적으로 지칭할 때

 * 2. this()

 * 3. this

 */

public class ThisDemo {

public static void main(String[] args) {

Student chulsu = new Student();

chulsu.setKor(90); //chulsu.kor = 90;

//chulsu.display();

}

}



public class Student {

private int kor;

public int getKor(){

return kor;

}

public void setKor(int kor){ //이름은 의미있는 이름으로 하는 것이 좋기 때문에 k로 해도 되지만 kor로.

this.kor = kor; //kor = kor; 을 하면 어떤 kor인지 컴퓨터는 알지 못한다.

this.display(); //this를 붙여주지 않아도 되지만(display라는 이름은 하나기 때문에), 컴파일러가 알아서 붙인다. 

}

public void display(){

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

}

}

----------------------------------------

/*

 * this --> self

 */

public class ThisDemo1 {

public static void main(String[] args) {

Demo original = new Demo();

original.setNumber(100);

Demo another = original.copy(); //주소복사

System.out.println("number = " + another.getNumber());

original.setNumber(50000);  //원본의 데이터를 바꾸면 주소복사이기 떄문에 값이 바뀐다.

System.out.println("number = " + another.getNumber());

}

} //단점 : encapsulation이 위배된다.

class Demo{

private int number;

public void setNumber(int number){this.number = number;}

public int getNumber() { return this.number;}

public Demo copy(){

return this; //자기의 주소자체를 넘겨주는 방식

}

}

출력:

number = 100

number = 50000

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class Box5 {

private int height;

private int width;

private int depth;

public Box5(){ //default constructor 

System.out.println("방금 객체가 생성됐습니다.");

}

public void display(){

System.out.printf("%d, %d, %d\n", this.width, this.height, this.depth);

}

protected void finalize(){ //destructor

System.out.println("방금 객체가 소멸됐습니다.");

}

}


public class EncapDemo5 {

public static void main(String[] args) {

Box5 box = new Box5();

box.display(); //생성자가 0으로 자동으로 초기화시켜준다.(멤버변수는 자동으로하고, 지역변수는 안한다)

box = null; //이렇게해도 box는 사라지지않는다.

System.gc(); //garbage collector 호출

//메모리의 box는 사라지지만, 메모리 heap에있는 Box5는 사라지지 않는다.

}

}


출력:

방금 객체가 생성됐습니다.

0, 0, 0

방금 객체가 소멸됐습니다.

-----------------------------------생성자의 오버로딩

public class Box6 {

private int height;

private int width;

private int depth;

public Box6(){ //default constructor 

this.width = this.height = this.depth = 0;

}

public Box6(int width, int height, int depth){ //constructor's overloading

this.width = width;

this.height = height;

this.depth = depth;

}

public int getVolume(){

return this.width * this.height * this.depth;

}

}


public class EncapDemo6 {

public static void main(String[] args) {

Box6 box = new Box6();

Box6 box1 = new Box6(10,20,30);

int result = box.getVolume();

System.out.println("박스의 부피 = " + result);

result = box1.getVolume();

System.out.println("박스1의 부피 = " + result);

}

}

출력:

박스의 부피 = 0

박스1의 부피 = 6000

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

constructor's overriding 

public class ConstructorDemo {

public static void main(String[] args) {

Date now = new Date();

now.display();

}

}

class Date{

int year, month, day;

public Date(){ //만약 만들어주지않으면 0년0월0일이 나올것이다. 이것은 없는 날이기 때문에 기본 생성자를 재정의 해줘야한다.

this.year = 2014; this.month = 3; this.day = 17; //이를 constructor's overriding 이라 한다.

}

void display(){

System.out.printf("%d년 %d월 %d일입니다", this.year, this.month, this.day);

}

}

출력:

2014년 3월 17일입니다

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Source-Generate Getter and Setter로 쉽게 만들 수 있다.

Source-Generate Constructor using Fields로 쉽게 생성자를 만들 수 있다.


public class Student {

private String hakbun, name;

private int kor, eng, mat, edp, tot;

private double avg;

private char grade;

public Student(String hakbun, String name, int kor, int eng, int mat, int edp, int tot, double avg, char grade) {

super();

this.hakbun = hakbun;

this.name = name;

this.kor = kor;

this.eng = eng;

this.mat = mat;

this.edp = edp;

this.tot = tot;

this.avg = avg;

this.grade = grade;

}

//필요에 맞게 선택해준다. 학번, 이름, 국어, 수학, 전산은 생성자를 만들었기 떄문에 set이 필요 없다(생성자가 setting 해주기 때문에)

public int getTot() {

return tot;

}

public void setTot(int tot) {

this.tot = tot;

}

public double getAvg() {

return avg;

}

public void setAvg(double avg) {

this.avg = avg;

}

public String getHakbun() {

return hakbun;

}

public int getKor() {

return kor;

}

public int getEng() {

return eng;

}

public int getMat() {

return mat;

}

public int getEdp() {

return edp;

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

성적관리프로그램

Student.java


public class Student {

private String hakbun, name;

private int kor, eng, mat, edp, tot, ranking;

private double avg;

private char grade;

public Student(String hakbun, String name, int kor, int eng, int mat, int edp) {

this.hakbun = hakbun;

this.name = name;

this.kor = kor;

this.eng = eng;

this.mat = mat;

this.edp = edp;

this.ranking = 1;

}

public void display(){

System.out.printf("%-10s%7s%5d%5d%5d%5d%5d%10.2f%5c%5d\n", this.hakbun, this.name, this.kor, this.eng, this.mat, this.edp, this. tot, this.avg, this.grade, this.ranking);

}

public int getTot() {

return tot;

}

public void setTot(int tot) {

this.tot = tot;

}

public int getRanking() {

return ranking;

}

public void setRanking(int ranking) {

this.ranking = ranking;

}

public double getAvg() {

return avg;

}

public void setAvg(double avg) {

this.avg = avg;

}

public char getGrade() {

return grade;

}

public void setGrade(char grade) {

this.grade = grade;

}

public int getKor() {

return kor;

}

public int getEng() {

return eng;

}

public int getMat() {

return mat;

}

public int getEdp() {

return edp;

}

}




Input.java


import java.util.Scanner;

import java.io.File;

import java.io.FileNotFoundException;

import javax.swing.JOptionPane;

public class Input {

private Scanner scan; //member variable

private Student [] array;

public Input(String path, Student [] array){

File file = new File(path); //멤버변수로 할 필요없이 지역변수로 하면 됨. Input에서 사용하고 다른데서 사용안하므로.

try{

scan = new Scanner(file);

}catch(FileNotFoundException ex){

JOptionPane.showMessageDialog(null, "File Not Found");

System.exit(-1);

}

this.array = array; //주소복사

}

public void input(){

for(int i = 0 ; i < this.array.length ; i++){

String line = this.scan.nextLine();

//System.out.println(line); //출력확인

String [] valueArray = line.split("\\s+"); //스페이스 한칸이상공백. 1101     한송이     78     87     83    78

this.array[i] = new Student(valueArray[0], valueArray[1], this.getInt(valueArray[2]), this.getInt(valueArray[3]), this.getInt(valueArray[4]), this.getInt(valueArray[5]));

}

}

int getInt(String value){

return Integer.parseInt(value);

}

}




Calc.java


public class Calc {

private Student [] array;


public Calc(Student[] array) {

this.array = array;

}

public void calc(){

for(Student s : this.array){

s.setTot(s.getKor() + s.getEng() + s.getMat() + s.getEdp());

s.setAvg(s.getTot() /4 );

s.setGrade(this.getGrade(s.getAvg()));

}

}

private char getGrade(double avg){

if(avg<=100 && avg>=90 ) return 'A';

else if(avg<90 && avg>=80) return 'B';

else if(avg<80 && avg>=70) return 'C';

else if(avg<70 && avg>=60) return 'D';

else return 'F';

}

}


Sort.java


public class Sort {

private Student [] array;

public Sort(Student [] array) {

this.array = array;

}

public void sort(){

for(int i = 0 ; i < this.array.length-1 ; i++){

for(int j = i+1 ; j < this.array.length ; j++){

if(this.array[i].getTot() > this.array[j].getTot()) {

//this.array[j].setRanking(this.array[j].getRanking() + 1); 아래 세줄을 한줄로 표현한.

int ranking = this.array[j].getRanking();

ranking++;

this.array[j].setRanking(ranking);

}else if(this.array[i].getTot() < this.array[j].getTot()){

this.array[i].setRanking(this.array[i].getRanking() + 1);

}

}

}

}

}




Output.java


public class Output {

private Student [] array;

public Output(Student[] array) {

this.array = array;

}

public void output(){

printLabel();

for(Student s : this.array)

s.display();

}

private void printLabel(){

System.out.println("                             <<성적관리프로그램>>");

}

}




Main.java


import javax.swing.JOptionPane;

public class Main {

public static void main(String[] args) {

Student [] array = new Student[12];

String msg = " 성적 데이터 파일 경로 : ";

String path = null;

do{

path = JOptionPane.showInputDialog(msg);

}while(path == null);

Input input = new Input(path, array);

input.input();

Calc calc = new Calc(array);

calc.calc();

Sort sort = new Sort(array);

sort.sort();

Output output = new Output(array);

output.output();

}

}

출력:

                                 <<성적관리프로그램>>

1101          한송이   78   87   83   78  326     81.00    B    6

1102          정다워   88   83   57   98  326     81.00    B    6

1103          그리운   76   56   87   78  297     74.00    C   10

1104          고아라   83   57   88   73  301     75.00    C    9

1105          사랑해   87   87   53   55  282     70.00    C   11

1106          튼튼이   98   97   93   88  376     94.00    A    1

1107          한아름   68   67   83   89  307     76.00    C    8

1108          더크게   98   67   93   78  336     84.00    B    4

1109          더높이   88   99   53   88  328     82.00    B    5

1110          아리랑   68   79   63   66  276     69.00    D   12

1111          한산섬   98   89   73   78  338     84.00    B    3

1112          하나로   89   97   78   88  352     88.00    B    2


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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

급여관리프로그램

Salary.java

public class Salary {

private int sabun;  

private int grade;

private int ho;

private int sudang;

private int bonbong;

private int tax;

private int sum;

public Salary(int sabun, int grade, int ho, int sudang) {

this.sabun = sabun;

this.grade = grade;

this.ho = ho;

this.sudang = sudang;

}

public int getTax() {

return tax;

}

public void setTax(int tax) {

this.tax = tax;

}

public int getSum() {

return sum;

}

public void setSum(int sum) {

this.sum = sum;

}

public int getSabun() {

return sabun;

}

public int getGrade() {

return grade;

}

public int getHo() {

return ho;

}

public int getSudang() {

return sudang;

}

public int getBonbong(){

return this.bonbong;

}

public void setBonbong(int bonbong){

this.bonbong = bonbong;

}

public void display(){

System.out.printf("%3d%7d%7d%,10d%,10d%10d%,12d\n", 

this.sabun, this.grade, this.ho, this.sudang, this.bonbong,

this.tax, this.sum);

}

}



Input.java

import java.util.Scanner;


public class Input {

private Scanner scan;

private Salary [] array;

public Input(Salary[] array) {

this.scan = new Scanner(System.in);

this.array = array;

}

public int input(){

int count = 0;

String i_o = null;

do{

count++;

System.out.print("사원번호 : ");  int sabun = this.scan.nextInt();

System.out.print("급 : ");            int grade = this.scan.nextInt();

System.out.print("호 : ");            int ho = this.scan.nextInt();

System.out.print("수당 : ");         int sudang = this.scan.nextInt();

System.out.print("입력/출력(I/O) : ");   i_o = this.scan.next();

this.array[count - 1] = new Salary(sabun, grade, ho, sudang);

}while(i_o.equals("I") || i_o.equals("i"));

return count;

}

}




Copy.java


public class Copy {

private int [][] copyArray;

private Salary [] array;

private int count;

public Copy(Salary [] array, int [][] copyArray, int count){

this.array = array;

this.copyArray = copyArray;

this.count = count;

}

public void copy(){

for(int i = 0 ; i < count ; i++){

this.copyArray[i][0] = this.array[i].getSabun();

this.copyArray[i][1] = this.array[i].getGrade();

this.copyArray[i][2] = this.array[i].getHo();

this.copyArray[i][3] = this.array[i].getSudang();

}

}

}




Calc.java

public class Calc {

private Salary [] array;

private int count;

public Calc(Salary[] array, int count) {

this.array = array;

this.count = count;

}

public void calc(){

for(int i = 0 ; i < count ; i++){

int money = this.getSalary(this.array[i].getGrade(), this.array[i].getHo());  //급여

int bonbong = money + this.array[i].getSudang();   //지급액

this.array[i].setBonbong(bonbong);

int tax = (int)(bonbong * this.getTaxRate(bonbong)) - this.getJojung(bonbong);  //세금

this.array[i].setTax(tax);

this.array[i].setSum(bonbong - tax);   //차인 지급액

}

}

private int getSalary(int grade, int ho){

int salary = 0;

switch(ho){

case 1 : salary = (grade == 1) ? 95000 : 80000; break; 

case 2 : salary = (grade == 1) ? 92000 : 75000; break;

case 3 : salary = (grade == 1) ? 89000 : 70000; break;

case 4 : salary = (grade == 1) ? 86000 : 65000; break;

case 5 : salary = (grade == 1) ? 83000 : 60000; break;

}

return salary;

}

private double getTaxRate(int bonbong){

return (bonbong < 70000) ? 0.0 :

      (bonbong >= 70000 && bonbong < 80000) ? 0.005 :

      (bonbong >= 80000 && bonbong < 90000) ? 0.007 : 0.012;   

}

private int getJojung(int bonbong){

return (bonbong < 70000) ? 0 :

              (bonbong >= 70000 && bonbong < 80000) ? 300 :

              (bonbong >= 80000 && bonbong < 90000) ? 500 : 1000;

}

}




Sort.java

public class Sort {

private Salary [] array;

private int count;

public Sort(Salary[] array, int count) {

this.array = array;

this.count = count;

}

public void sort(){

for(int i = 0 ; i < this.count - 1 ; i++){

for(int j = 0 ; j < this.count - 1 - i ; j++){

if(this.array[j].getSabun() > this.array[j + 1].getSabun()) swap(j, j + 1);

}

}

}

private void swap(int first, int second){

Salary temp = this.array[first];

this.array[first] = this.array[second];

this.array[second] = temp;

}

}




Output.java

public class Output {

private Salary [] array;

private int [][] copyArray;

private int count;


public Output(Salary[] array, int [][] copyArray, int count) {

this.array = array;

this.copyArray = copyArray;

this.count = count;

}

public void output(){

this.printLabel();

this.printDash();

this.printLabel1();

this.printDash();

for(int i = 0 ; i < count ; i++){

this.array[i].display();

}

this.printDash();

System.out.println("\n입력데이타 출력");

for(int i = 0 ; i < count ; i++){

for(int j = 0 ; j < copyArray[i].length ; j++){

System.out.printf("%d\t", copyArray[i][j]);

}

System.out.println();

}

}

private void printLabel(){

System.out.println("\n\n");

System.out.println("                          <<급여 관리 프로그램>>");

}

private void printLabel1(){

System.out.println("사번     급수      호       수당      지급액         세금     차인지급액");

}

private void printDash(){

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

}

}




Main.java

public class Main {

public static void main(String[] args) {

Salary [] array = new Salary[5];

Input input = new Input(array);

int count = input.input();

int [][] copyArray = new int[count][4];

Copy copy = new Copy(array, copyArray, count);

copy.copy();

Calc calc = new Calc(array, count);

calc.calc();

Sort sort = new Sort(array, count);

sort.sort();

Output output = new Output(array, copyArray, count);

output.output();

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

이름, 나이, 몸무게, 키 입력 프로그램.

public class Human {

String name;

int age;

double weight;

double ki;

}//C언어 기준으로 말하면 구조체 타입 선언.


import java.util.Scanner;

public class EncapDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

Human chulsu; //Human type 선언

chulsu = new Human();

//System.out.println(chulsu); //자바는 번지를 찍을 수 없다.

System.out.println("Name : ");

chulsu.name = scan.nextLine();

System.out.println("Age : ");

chulsu.age = scan.nextInt();

System.out.println("Weight : ");

chulsu.weight = scan.nextDouble();

System.out.println("Ki : ");

chulsu.ki = scan.nextDouble();

System.out.printf("name = %s , age = %d, weight = %.1f, ki = %.1f\n", chulsu.name, chulsu.age, chulsu.weight, chulsu.ki);

}

}

출력 :

Name : 

설 운도

Age : 

48

Weight : 

65.2

Ki : 

172.3

name = 설 운도 , age = 48, weight = 65.2, ki = 172.3

---------------------------------

위의 코드를 method를 나눠서(위에서 썼던 Human class를 사용한다)

import java.util.Scanner;

public class EncapDemo1 {

public static void main(String[] args) {

Human chulsu = new Human();

EncapDemo1 ed = new EncapDemo1();  //static이 아닌 멤버들을 메모리에 올려주기위해

ed.input(chulsu);

ed.output(chulsu);

}

void input(Human h){

Scanner scan = new Scanner(System.in);

System.out.println("Name : ");

h.name = scan.nextLine();

System.out.println("Age : ");

h.age = scan.nextInt();

System.out.println("Weight : ");

h.weight = scan.nextDouble();

System.out.println("Ki : ");

h.ki = scan.nextDouble();

}

void output(Human h){

System.out.printf("name = %s , age = %d, weight = %.1f, ki = %.1f\n", h.name, h.age, h.weight, h.ki);

}

}

---------------------------------

(위에서 썼던 Human class를 사용한다)

import javax.swing.JOptionPane;

public class EncapDemo2 {

public static void main(String[] args) {

Human [] array; //배열의 선언

array = new Human[2];

Human chulsu, younghee; //타입선언

EncapDemo2 ed = new EncapDemo2();

ed.input(array);

ed.output(array);

}

void input(Human [] array){

String [] titleArray = {"Name : ", "Age : ", "Weight : ", "Ki : "};

String [] result = new String[titleArray.length];

int i = 0;

while(i<array.length){

array[i] = new Human();

for(int j = 0; j <titleArray.length; j++){

result[j] = JOptionPane.showInputDialog(titleArray[j]);

}

array[i].name = result[0];

array[i].age = Integer.parseInt(result[1]);

array[i].weight = Double.parseDouble(result[2]);

array[i].ki = Double.parseDouble(result[3]);

i++;

}

}

void output(Human [] array){

for(Human h : array){

System.out.printf("name = %s, age = %d, weight = %.1f, ki = %.1f\n", h.name, h.age, h.weight, h.ki);

}

}

}

출력:

name = 설운도, age = 53, weight = 74.3, ki = 176.5

name = 김하나, age = 13, weight = 40.2, ki = 148.1

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

성적관리 프로그램

public class Student {

String hakbun, name;

int kor, eng, mat, tot;

double avg;

}


import java.util.Scanner;

public class EncapDemo3 {

public static void main(String[] args) {

Student s = new Student();

EncapDemo3 ed = new EncapDemo3();

ed.input(s);

ed.calc(s);

ed.output(s);

}

void input(Student s){

Scanner scan = new Scanner(System.in);

System.out.println("학번 : "); s.hakbun = scan.next();

System.out.println("이름 : "); s.name = scan.next();

System.out.println("국어 : "); s.kor = scan.nextInt();

System.out.println("영어 : "); s.eng = scan.nextInt();

System.out.println("수학 : "); s.mat = scan. nextInt();

}

void calc(Student s){

s.tot = s.kor + s.eng + s.mat;

s.avg = s.tot/3.;

switch((int)(s.avg/10)){

case 10 : 

case 9 : s.grade = 'A'; break;

case 8 : s.grade = 'B'; break;

case 7 : s.grade = 'C'; break;

case 6 : s.grade = 'D'; break;

default : s.grade = 'F';

}

}

void output(Student s){

System.out.printf("학번 = %s, 이름 = %s\n", s.hakbun, s.name);

System.out.printf("국어 = %d, 영어 = %d, 수학 = %d, 총점 = %d, 평균 = %.2f", s.kor, s.eng, s.mat, s.tot, s.avg);

}

}

출력:

학번 : 

1101

이름 : 

김강민

국어 : 

70

영어 : 

65

수학 : 

89

학번 = 1101, 이름 = 김강민

국어 = 70, 영어 = 65, 수학 = 89, 총점 = 224, 평균 = 74.67

----------------------------------------

성적관리프로그램1

위의 Student class를 사용.

import java.util.Scanner;

public class EncapDemo4 {

public static void main(String[] args){

Student [] array = new Student[100]; //학생수는 최대 100명

EncapDemo4 ed = new EncapDemo4();

int number = ed.input(array);

ed.calc(array, number);

ed.output(array, number);

}

int input(Student [] array){ //void input(Student [] array)와 Student[]?

Scanner scan = new Scanner(System.in);

int count = 0;

String y_n = null; //지역변수는 초기치를 줘야한다.

do{

count++;

Student s = new Student();

System.out.printf("%d번째 학생\n", count);

System.out.print("학번 : "); s.hakbun = scan.next();

System.out.print("이름 : "); s.name = scan.next();

System.out.print("국어 : "); s.kor = scan.nextInt();

System.out.print("영어 : "); s.eng = scan.nextInt();

System.out.print("수학 : "); s.mat = scan.nextInt();

array[count-1] = s;

System.out.print("Agagin(y/n) ? : ");

y_n = scan.next();

}while(y_n.equals("Y") || y_n.equals("y"));

return count;

}

void calc(Student [] array, int count){

int i = 0;

while(i<count){

array[i].tot = array[i].kor + array[i].eng + array[i].mat;

array[i].avg = array[i].tot/3.;

array[i].grade = getGrade(array[i].avg);

i++;

}

}

char getGrade(double avg){

char grade = '\u0000'; //널값.='\n'. 지역변수에는 언제나 초기값을 주어야한다.

switch((int)(avg/10)){

case 10 : 

case 9 : grade = 'A'; break;

case 8 : grade = 'B'; break;

case 7 : grade = 'C'; break;

case 6 : grade = 'D'; break;

default : grade = 'F';

}

return grade;

}

void output(Student [] array, int count){

for(int i = 0 ; i<count; i++){//넣어주지않은 학생값이 있으므로 for(int su : array) 사용하지 않는다.

System.out.printf("학번 = %s, 이름 = %s\n", array[i].hakbun, array[i].name);

System.out.printf("국어 = %d, 영어 = %d, 수학 = %d, 총점 = %d, 평균 = %.2f, 학점 = %c\n", array[i].kor, array[i].eng, array[i].mat, array[i].tot, array[i].avg, array[i].grade);

}

}

}

출력 :

1번째 학생

학번 : 1101

이름 : 이미자

국어 : 100

영어 : 90

수학 : 80

Agagin(y/n) ? : y

2번째 학생

학번 : 1102

이름 : 설운도

국어 : 56

영어 : 78

수학 : 89

Agagin(y/n) ? : n

학번 = 1101, 이름 = 이미자

국어 = 100, 영어 = 90, 수학 = 80, 총점 = 270, 평균 = 90.00, 학점 = A

학번 = 1102, 이름 = 설운도

국어 = 56, 영어 = 78, 수학 = 89, 총점 = 223, 평균 = 74.33, 학점 = C

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

성적관리프로그램2 (파싱하는 방법)

Student.java

public class Student {

String hakbun, name;

int kor, eng, mat, edp, tot;

double avg;

char grade;

}



Input.java

import java.util.Scanner;

import java.io.File;

import java.io.FileNotFoundException;


public class Input {

int input(Student [] array){

String path = "./sungjuk_utf8.dat";

File file = new File(path);

Scanner scan = null;

try{

scan = new Scanner(file);

}catch(FileNotFoundException ex){

System.out.println("File Not Found");

System.exit(-1);;

}

int count = 0;

String str = null; //지역변수 초기화

try{

while((str = scan.nextLine()) != null){

count++;

String [] valueArray = str.split("\\s+"); //자른 것을 배열에 넣어줌. \를 \해주어 다른 것으로 생각안하게.

array[count - 1] = new Student();

array[count - 1].hakbun = valueArray[0];

array[count - 1].name = valueArray[1];

array[count - 1].kor = Integer.parseInt(valueArray[2]);

array[count - 1].eng = Integer.parseInt(valueArray[3]);

array[count - 1].mat = Integer.parseInt(valueArray[4]);

array[count - 1].edp = Integer.parseInt(valueArray[5]);

//if(str == null) break; //파일의 끝

//System.out.println(str); //input 잘 나오나 확인한 것

//1101 한송이 78 87 83 78 이 문자열을 어떻게 자를까?

/*

* Java에서 문자열 파싱(parsing)방법 3가지

* 1. String class : String [] split(String regex) - 이것을 사용하고 나머진 다음에.

*  space bar  : \s

*  빈도 : *, ?, +

*   space bar 한 개 이상 ---> \s+

* 2. java.util.StringTokenizer class

* 3. java.util.Scanner

*/

}

}catch(Exception e){} //마지막에 Exception이 안나오게..

return count;

}

}



Calc.java

public class Calc {

void calc(Student [] array, int count){

int i = 0;

while(i<count){

array[i].tot = array[i].kor + array[i].eng + array[i].mat + array[i].edp;

array[i].avg = array[i].tot/4.;

array[i].grade = getGrade(array[i].avg);

i++;

}

}

char getGrade(double avg){

char grade = '\u0000'; //널값.='\n'. 지역변수에는 언제나 초기값을 주어야한다.

switch((int)(avg/10)){

case 10 : 

case 9 : grade = 'A'; break;

case 8 : grade = 'B'; break;

case 7 : grade = 'C'; break;

case 6 : grade = 'D'; break;

default : grade = 'F';

}

return grade;

}

}



Sort.java

public class Sort {

void insertionSort(Student [] array, int count){

int i, j;

Student key;

for(i=1; i<count ; i++){

key = array[i];

for(j = i-1 ; j>=0 && array[j].tot < key.tot ; j--){

array[j+1] = array[j];

}

array[j+1] = key;

}

}

}



Output.java

public class Output {

void output(Student [] array, int count){

for(int i = 0 ; i<count; i++){//넣어주지않은 학생값이 있으므로 for(int su : array) 사용하지 않는다.

System.out.printf("%-10s%6s%5d%5d%5d%5d%5d%10.2f%5c\n", 

array[i].hakbun, array[i].name, array[i].kor, array[i].eng, array[i].mat,array[i].edp, 

array[i].tot, array[i].avg, array[i].grade);

}

}

}



Main.java

public class Main {

public static void main(String[] args) {

Student [] array = new Student[100];

Input input = new Input();

int count = input.input(array);

Calc calc = new Calc();

calc.calc(array, count);

Sort sort = new Sort();

sort.insertionSort(array, count);

Output output = new Output();

output.output(array, count);

}

}

출력:

1106         튼튼이   98   97   93   88  376     94.00    A

1112         하나로   89   97   78   88  352     88.00    B

1111         한산섬   98   89   73   78  338     84.50    B

1108         더크게   98   67   93   78  336     84.00    B

1109         더높이   88   99   53   88  328     82.00    B

1101         한송이   78   87   83   78  326     81.50    B

1102         정다워   88   83   57   98  326     81.50    B

1107         한아름   68   67   83   89  307     76.75    C

1104         고아라   83   57   88   73  301     75.25    C

1103         그리운   76   56   87   78  297     74.25    C

1105         사랑해   87   87   53   55  282     70.50    C

1110         아리랑   68   79   63   66  276     69.00    D

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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

Private 사용.

public class Person {

private String name;

private int age;

public void set(String n, int a){//이름과 나이를 동시에 써줘야한다.

name = n;

age = a;

}

public void set(String n){//이름만 바꿀 수 있게

name = n;

}

public void set(int a){

age = a;

}

public String getName(){

return name;

}

public int getAge(){

return age;

}

}


public class EncapDemo5 {

public static void main(String[] args){

Person p = new Person();

// p.name = "설운도";

// p.age = 45;

p.set("설운도", 45);

// System.out.println("Name : "+ p.name);

// System.out.println("Age : " + p.age);

System.out.println("name : " + p.getName());

System.out.println("Age : " + p.getAge());

p.set("이미자");

System.out.println("name : " + p.getName());

System.out.println("Age : " + p.getAge());

}

}

출력:

name : 설운도

Age : 45

name : 이미자

Age : 45

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

생성자

Person1.java

public class Person1 {

private String name;

private int age;

public Person1(){ //이름이 같고 파라미터가 다르면 오버로딩. 

System.out.println("객체생성성공");

}

public Person1(String name){ 

System.out.println("객체생성성공");

}

public Person1(String n, int a){  //생성자 method는 class의 이름과 똑같아야 한다.

name = n;

age = a;

System.out.println("방금 객체가 생성됐습니다");

}

public void setName(String n){  //setter

name = n;

}

public String getName(){  //getter

return name;

}

public void setAge(int a){

age = a;

}

public int getAge(){

return age;

}

}

EncapDemo6.java

import java.util.Calendar;

public class EncapDemo6 {

public static void main(String[] args) {

Integer in = new Integer(); //Integer는 ()안이 비어있게 만들지 못한다.

String str = new String(); //String은 ()안이 비어있어도 만들 수 있다.

Calendar cal = new Calendar(); //Calendar는 ()비어있어도 만들 수 있지만 protected기 때문에 접근이 안된다.

Math m = new Math(); //Math는 생성자가 없어서, 만들 수 없다.

// Person1 p = new Person1("설운도", 45); //객체초기화

// Person1 p1 = new Person1("이미자",60); //객체를 만들면서 동시에 넣어줌.

// Person1 p2 = new Person1("에일리", 26);

/* p.setName("설운도");

p.setAge(45);

System.out.println("name : " + p.getName());

System.out.println("age : " + p.getAge());*/

//Person1 p;

//p = new Person1("설운도", 45);

}

}


어제 했던 아래 코드를 실행시킬 때 터미널창으로 나가서 실행시킬 필요는 없다.

public class ArrayDemo {

public static void main(String[] args) {

int first = Integer.parseInt(args[0]); //"4" --> 4

   int second = Integer.parseInt(args[2]); //"7" --> 7

String op = args[1];

int result =0;

switch(op){

case "+" : result = first + second; break;

case "-"  : result = first - second; break;

case "x"  : result = first * second; break;

case "/"  : result = first / second; break;

case "%" : result = first % second; break;

}

System.out.printf("%d %s %d = %d\n", first, op, second, result);

}

}

Run-run configuration 에 들어가서 Arguments 탭에 넣어준다. (예) 4 + 7 )

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

HelloWorld를 출력하는 8가지 방법.

//1. 주소로접근

public class HelloWorld1 {

String msg = "Hello, World"; //member(instance) variable

public static void main(String[] args) {

//String msg = " Hello, World";  //local(temporary, stack, automatic) variable

HelloWorld1 hw = new HelloWorld1(); //멤버 변수를 메모리에 올려서 접근 가능하게 함.

System.out.println(hw.msg);

}

}

-------------------------------

//2. 멤버변수를 static으로 만들어줌

public class HelloWorld2 {

static String msg = "Hello, World"; //member(instance) variable

public static void main(String[] args) {

System.out.println(HelloWorld2.msg);

}

}

-------------------------------

//3. 다른 클래스의 주소로 접근

public class HelloWorld3 {

public static void main(String[] args){

Demo d = new Demo();

System.out.println(d.msg);

}

}

class Demo{

String msg = "Hello, World"; //member variable

}

-------------------------------

//4. 클래스 변수가 static으로 만들어 만들어져 있으므로 클래스이름으로 접근.

public class HelloWorld4 {

public static void main(String[] args){

System.out.println(Test.msg);

}

}

class Test{

static String msg = "Hello, World"; //class variable

}

-------------------------------

//5. 클래스의 주소로 접근

public class HelloWorld5 {

public static void main(String[] args){

HelloWorld5 hw =new HelloWorld5();

hw.display();

}

void display(){ //member(instance) method

System.out.println("Hello, World");

}

}

-------------------------------

//6. static method 로 사용.

public class HelloWorld6 {

public static void main(String[] args){

//static method에 접근하는

//1. 그냥쓴다.

//display();

//2.굳이 주소를 만든다.

//HelloWorld6 hw = new helloWorld6();

//hw.display();

//3. 클래스이름으로 접근한다.

HelloWorld6.display();

}

static void display(){

System.out.println("Hello, World");

}

}

-------------------------------

//7.

public class HelloWorld7 {

public static void main(String[] args){

Demo1 d = new Demo1();

d.display();

//위의 두 줄을 축약형으로 쓰면

//new Demo1().display(); 이렇게 간단히 쓸 수 있다. display에 한번만 접근할 때만 사용.

}

}

class Demo1{ //자바는 한 파일에 같은 클래스의 이름을 사용할 수없다.

void display(){

System.out.println("Hello, World");

}

}

-------------------------------

//8. 클래스 이름으로 접근

public class HelloWorld8 {

public static void main(String[] args){

Test1.display();

Demo2.display();

}

}

class Test1{

static void display(){

System.out.println("Hello, World");;

}

}

class Demo2{

static void display(){

System.out.println("헬로월드");

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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

Method 필수 3요소 괄호, 이름, 리턴타입이 있어야 한다.

public class MethodDemo {

public static void main(String[] args) {

MethodDemo md = new MethodDemo();

md.getSum(); //call by Name --> 자바에서는 Pass by Name 이라 한다.

md.getSum();

md.getSum();

}

void getSum(){

int sum = 0;

for(int i = 1 ; i <= 100 ; i ++)

sum += i;

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

}

} //class 안에만 있다면 method가 위에있든 main이 위에 있든 상관이 없다.

---------------------------------

//call by value

public class MethodDemo1 {

public static void main(String[] args) {

MethodDemo1 md = new MethodDemo1();

md.getSum(30); //call by value --> 자바에서는 pass by value

md.getSum(50);

md.getSum(80);

}

void getSum(int end){

int sum = 0;

for(int i = 1 ; i <= end ; i ++)

sum += i;

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

}

}

------------시작값과 끝 값을 보내주면.

public class MethodDemo1 {

public static void main(String[] args) {

MethodDemo1 md = new MethodDemo1();

md.getSum(20,30); //call by value --> 자바에서는 pass by value

md.getSum(10,50);

md.getSum(1,100);

}

void getSum(int start, int end){

int sum = 0;

for(int i = start ; i <= end ; i ++)

sum += i;

System.out.printf("%d부터 %d까지의 합은 %d\n", start, end, sum);

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

call by value로 factorial

public class MethodDemo2 {

public static void main(String[] args) {

MethodDemo2 md = new MethodDemo2();

md.getFactorial(4);

md.getFactorial(7);

md.getFactorial(3);

}

void getFactorial(int su){

int gob = 1;

for(int i = su; i>0 ; i--){

gob *= i;

}

System.out.printf("%d! = %d\n", su, gob);

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

위의 getFactorial method를 리턴으로 받아서 출력.

public class MethodDemo2 {

public static void main(String[] args) {

MethodDemo2 md = new MethodDemo2();

int su = 4;

int result = md.getFactorial(su);

System.out.printf("%d! = %d\n", su, result);

su = 7;

result = md.getFactorial(su);

System.out.printf("%d! = %d\n", su, result);

su = 3;

result = md.getFactorial(su);

System.out.printf("%d! = %d\n", su, result);

}

int getFactorial(int su){

int gob = 1;

for(int i = su; i>0 ; i--){

gob *= i;

}

return gob;

}

}

------위의 코드를 조금짧게 줄여보자.


public class MethodDemo2 {

public static void main(String[] args) {

MethodDemo2 md = new MethodDemo2();

int su = 4;

md.getFactorial(su);

su = 7;

md.getFactorial(su);

su = 3;

md.getFactorial(su);

}

void getFactorial(int su){

int gob = 1;

for(int i = su; i>0 ; i--){

gob *= i;

}

display(su,gob); //같은 class 안의 method는 같은 멤버이기 때문에 주소 호출이 필요하지 않다. 동일주소에 있고, 둘다 메모리에 올려져있기 때문.

}

void display(int su, int result){ //member method

System.out.printf("%d! = %d\n", su, result);

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

method 호출 (static이 있음과 없음의 차이)

public class MethodDemo3 { //호출 하는 쪽이 안하는 쪽을 본다.

public static void main(String[] args) {

aaa();

new MethodDemo3().bbb();

}

static void aaa(){

System.out.println("aaa");

}

void bbb(){

System.out.println("bbb");

ccc(); //ccc는 static이기 때문에 bbb보다 먼저 메모리에 올라와있기 때문에 그냥 호출하면 된다.

}

static void ccc(){

System.out.println("ccc");

new MethodDemo3().ddd();//아직 만들어지지 않은 ddd에 접근하려면 ddd의 주소가 필요하다.

}

void ddd(){

System.out.println("ddd");

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

자바의 return

public class MethodDemo4 {

public static void main(String[] args) {

String result = new MethodDemo4().getReturn(7);

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

}

String getReturn(int su){

if(su % 2 == 0) return "Hello"; //리턴은 조건문 안에 쓴다면 한개이상 써도 된다.

System.out.println("World");

return "Java";

//return "Hello";

//return "World";//위에 이미 hello를 리턴했기 때문에 에러

//System.out.println("World"); //리턴 밑에는 어떤 코드도 있으면 안된다. 에러발생.

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

call by value - 다른 메소드에 가서 값이 변경되었더라도 다시 돌아오면 그 값은 변경되지 않았다.

//값 복사는 premitive 타입(8개와 string 총 9개)은 절대 원본에 영향을 주지않는다.(

public class MethodDemo5 {

public static void main(String[] args) {

int num = 8;

new MethodDemo5().change(num);

System.out.println("in main() num = " + num);

}

void change(int num){

num *= 100;

System.out.println("in change () num = " + num);

}

}

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

//Call by value

public class MethodDemo6 {

public static void main(String[] args) {

int a = 5, b = 9;

System.out.printf("Before swapping a = %d, b = %d\n", a, b);

new MethodDemo6().swap(a,b);

System.out.printf("After swapping a = %d, b = %d\n", a, b);

}

void swap(int a, int b){

int temp = a; a = b; b =temp;

System.out.printf("in swapping a = %d, b = %d\n", a, b);

}

}

출력:

Before swapping a = 5, b = 9

in swapping a = 9, b = 5

After swapping a = 5, b = 9

------------------------------------

//위의 코드를 Call by Reference(Pass by Reference)

//1번째 방법. 배열로 넘겨 준다.

public class MethodDemo7 {

public static void main(String[] args) {

int [] array = {5,9};

System.out.printf("Before swapping a = %d, b = %d\n", array[0], array[1]);

new MethodDemo7().swap(array);

System.out.printf("After swapping a = %d, b = %d\n", array[0], array[1]);

}

void swap(int [] array){

int temp = array[0];

array[0] = array[1];

array[1] = temp;

System.out.printf("in swapping a = %d, b = %d\n", array[0], array[1]);

}

}

출력 :

Before swapping a = 5, b = 9

in swapping a = 9, b = 5

After swapping a = 9, b = 5

--------------

//2번째 방법

public class MethodDemo8 {

public static void main(String[] args) {

Swap swap = new Swap();

swap.a = 5; swap.b = 9; 

System.out.printf("Before swapping a = %d, b = %d\n", swap.a, swap.b);

new MethodDemo8().swap(swap);

System.out.printf("After swapping a = %d, b = %d\n", swap.a, swap.b);

}

void swap(Swap swap){

int temp = swap.a;

swap.a = swap.b;

swap.b = temp;

System.out.printf("in swapping a = %d, b = %d\n", swap.a, swap.b);

}

}

//클래스를 하나 더만들어줘서

public class Swap {

int a,b;

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

파일에 입력된 내용을 가져오는 작업.

import java.util.Scanner;

import java.io.File; //File을 사용하기 위해

import java.io.FileNotFoundException;

public class MethodDemo9 {

public static void main(String[] args) {

MethodDemo9 md = new MethodDemo9();

String [] array = md.input();

md.output(array);

}

String [] input(){

System.out.print("파일 경로 : ");

Scanner scan = new Scanner(System.in);

String path = scan.nextLine();

File file = new File(path);

try{

scan = new Scanner(file);

}catch(FileNotFoundException ex){ //파일을 못찾았을때 처리. 안 쓰면 에러발생.

System.out.println("File Not Found");

System.exit(-1); //비정상종료.

}

String [] array = new String[12];

for(int i = 0 ; i<array.length ; i++){

array[i] = scan.nextLine();

}

return array;

}

void output(String [] array){

for(String str : array) System.out.println(str);

}

}

출력:

파일 경로 : sungjuk_utf8.dat

1101     한송이     78     87     83    78

1102     정다워     88     83     57    98

1103     그리운     76     56     87    78

1104     고아라     83     57     88    73

1105     사랑해     87     87     53    55

1106     튼튼이     98     97     93    88

1107     한아름     68     67     83    89

1108     더크게     98     67     93    78

1109     더높이     88     99     53    88

1110     아리랑     68     79     63    66

1111     한산섬     98     89     73    78

1112     하나로     89     97     78    88

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

...의 사용

//Variable Argument

public class MethodDemo10 {

public static void main(String[] args) {

MethodDemo10 md= new MethodDemo10();

md.display(1,2,3,4,5,6,7,8,9);

md.display(1,2,3);

md.display(4,5,6,7,8,9);  //같은 method로 보내지만 각 보내는 argument 수가 다르다면

}

void display(int... array){

for(int su : array) System.out.print(su + "\t");

System.out.println();

}

}

출력:

1 2 3 4 5 6 7 8 9

1 2 3

4 5 6 7 8 9

------

만약 보내는 개수와 타입이 제각각이라면 Object로 받는다.

//Variable Argument

public class MethodDemo10 {

public static void main(String[] args) {

MethodDemo10 md= new MethodDemo10();

Swap swap = new Swap();

swap.a = 9; swap.b = 10;

md.display(1,'M', 89.5, false, swap);

md.display(90,true);

md.display(3.14, "Hello,World", 5050);

}

void display(Object... array){ //모든 type의 부모는 object이다. 어떤형을 넘기든 Object로 다 받을 수 있다.

for(int i = 0; i< array.length; i++){

if(!array[i].getClass().getName().equals("Swap"))//class읽어서 이름이 Swap객체와 비교하여 같지 않다면

System.out.println(array[i] + "\t");

else{ //Swap Type

Swap s = (Swap)array[i];

System.out.println("(" + s.a +"," + s.b + ")");

}

}

System.out.println();

}

}

public class Swap {

int a,b;

}

출력:

1

M

89.5

false

(9,10)


90

true


3.14

Hello,World

5050

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

//Recursive Call(재귀 호출)

public class MethodDemo11 {

public static void main(String[] args) {

new MethodDemo11().print(1);

}

void print(int su){

System.out.print(su + "\t");

if(su == 5) return;

else print(++su);

}

}

출력 : 1 2 3 4 5

//재귀 호출은 메모리낭비가 심해서 잘 쓰질 않는다.

//피보나치 수열, 퀵정렬 , 바이너리 서치

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

피보나치수열

//Recursive Call(재귀 호출)

public class MethodDemo11 {

public static void main(String[] args) {

int n = 7;

int result = new MethodDemo11().fibo(n);

System.out.printf("%d번째의 피보나치 수열의 값은 %d\n", n, result);

}

int fibo(int n){

if(n <= 2) return 1;

else return fibo(n-1) + fibo(n-2);

}

}

출력:

7번째의 피보나치 수열의 값은 13

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Overload //method가 이름이 같은 것으로 정의. 이름이 같으면 파라미터로 구별. 이름이 같게하는 이유는 동작이 같기 때문에.

//파라미터의 이름과 method의 리턴타입은 관계없다.


public class MethodDemo12 {

public static void main(String[] args) {

}

void print(){}

void print(int a){} //void print(int b){} 이것은 같다. 파라미터의 이름은 구별하지 않기 때문에

void print(double a){}

void print(int a, int b){}

void print(double a, double b){}

void print(int a, int b, int c){}

}

//이런식으로 사용가능하다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

클래스의 이름으로 접근하게 끔 만들때는 static으로 만든다.

main이 static인 이유는 new없이(주소없이) main을 접근하기 위해서....

main뿐 아니라 나머지도 이유는 같다. 주소 없이 접근하기 위해서...

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

UML tool 설치

http://staruml.sourceforge.net/en/download.php 사이트에서 다운(windows용).

staruml-5.0-with-cm.exe 다운.

리눅스에서 사용을 위해 와인을 깔아준다.

터미널에서 sudo add-apt-repository ppa:ubuntu-wine/ppa 엔터.

repository를 추가해줬으니 캐시업데이트 sudo apt-get update 해줌.

sudo apt-get install wine1.7 winetricks 로 wine1.7버전을 다운해줌. wine은 에뮬레이터, winetricks는 환경설정.

검색해서 wine쳐서 configure wine 선택. 환경설정을 볼 수 있다.

다음은 winetricks를 열어본다. 그리고 select the default wineprefix 선택. 여기서 폰트등 바꿀 수 있다.

wine을 사용하면 editplus도 윈도우처럼 사용 가능. 에디트플러스를 다운받고.

다운받은 에디트플러스를 오른쪽버튼 -> open with -> wine windows program loader으로 열어줌. 설치 해주고 끝.

아까 다운 받은 staruml-5.0-with-cmd.exe 을 역시 wine windows program loader 로 설치해줌.

설치중 편의를 위해 바탕화면에 아이콘 체크해주고, 중간에 창이 하나 뜨면 ignore눌러줌. 설치완료.

class 이름을 바꾸면 오류가 발생하는데 이것을 해결하기 위하여 

http://www.javaexpert.co.kr/category/%EB%A6%AC%EB%88%85%EC%8A%A4  에서 15번부터 실행해준다. 

그리고 다시 starUML다운받은 것을 다시 설치해주면 된다.





Chapter 7. Methods.pdf


출처 : www.javaexpert.co.kr



Label break 예제

public class BreakLabelDemo {

public static void main(String[] args) {

int count=0;

first :

for(int i = 0 ; i < 4 ; i++){

second :

for(int j = 0 ; j < 5 ; j++){

for(int k = 0 ; k < 2 ; k++){

System.out.printf("(%d, %d, %d)\n", i, j, k);

count++;

if(i == 2 && j == 3 && k ==0) break first;

}

System.out.println("반복 k 끝");

}

System.out.println("반복 j 끝");

}

System.out.println("반복 i 끝");

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

}

}

출력:

(0, 0, 1)

반복 k 끝

(0, 1, 0)

(0, 1, 1)

반복 k 끝

(0, 2, 0)

(0, 2, 1)

반복 k 끝

(0, 3, 0)

(0, 3, 1)

반복 k 끝

(0, 4, 0)

(0, 4, 1)

반복 k 끝

반복 j 끝

(1, 0, 0)

(1, 0, 1)

반복 k 끝

(1, 1, 0)

(1, 1, 1)

반복 k 끝

(1, 2, 0)

(1, 2, 1)

반복 k 끝

(1, 3, 0)

(1, 3, 1)

반복 k 끝

(1, 4, 0)

(1, 4, 1)

반복 k 끝

반복 j 끝

(2, 0, 0)

(2, 0, 1)

반복 k 끝

(2, 1, 0)

(2, 1, 1)

반복 k 끝

(2, 2, 0)

(2, 2, 1)

반복 k 끝

(2, 3, 0)

반복 i 끝

count = 27

-------------------------

다중 반복문일때만 효과가 있다.

public class BreakLabelDemo1 {

public static void main(String[] args) {

first :

for(int i = 0 ; i <= 100 ; i++){

System.out.print(i + "\t");

if(i == 30 ) break first; //break만 써줘도 결과는 같다.

}

System.out.println("반복 i의 끝");

}

}

출력:

0 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 26 27 28 29 30 반복 i의 끝

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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

배열

//배열을 초기화하는 세가지 방법

public class ArrayDemo {

public static void main(String[] args) {

//1. 배열의 선언

int [] array;

//2. 배열의 생성

array = new int[4];

//3. 배열의 값을 할당

array[0] = 5; array[1] = 6; array[2] = 7; array[3] = 8;

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

//1. 배열의 선언

int [] array;

//2. 배열의 생성 및 할당

array = new int[]{5,6,7};

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

int [] array = {5,6,7,8,9};

//세번째 방법의 단점은 선언과 초기화를 다른라인에 하면 에러가 발생한다. 세번째 방법은 무조건 동일라인에 선언과 초기화를 해주어야한다.

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

배열을 이용한 성적관리

import java.util.Scanner;


public class ArrayDemo1 {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int [] array;

array = new int[4]; //국어, 영어, 수학, 총점

String [] subject = {"국어점수 : ", "영어접수 : ", "수학점수 : "};

for( int i = 0 ; i < subject.length ; i++) {

System.out.print(subject[i]);

array[i] = scan.nextInt();

array[3] += array[i];

}

System.out.printf("국어 = %d, 영어 = %d, 수학 = %d, 총점 = %d", array[0], array[1], array[2], array[3]);

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

input과 output을 함수로 나누고 랜덤값을 배열로 입력받아 총점까지 출력.

public class ArrayDemo2 {

public static void main(String[] args) {

int [] array = input();

int sum = calc(array);

output(sum, array);

}

static int [] input(){ //리턴을 int [] 을 함. //static을 쓰는 이유는 주소없이 접근하므로

int [] array = new int[4];

for (int i = 0 ; i < array.length ; i++)

array[i] = (int)(Math.random() * 10 + 1);

return array;

}

static int calc(int [] array){

int sum = 0;

for(int su : array) sum += su;

return sum;

}

static void output(int sum, int [] array){

for (int su : array) System.out.print(su + "\t");

System.out.println("\nSum = " + sum);

}

}

출력 :

7 7 7 9

Sum = 30

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class ArrayDemo3 {

public static void main(String[] args) {

char array[] = {'H','e','l','l','o','\0'}; //널을 포함해야 str과 같다. 

String str = "Hello";

array[0] = 'C';

for(char ch : array) System.out.print(ch); //문제없이 Cello 출력

System.out.println();

str[0] = 'C'; //오류발생

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

}

}

------------------

public class ArrayDemo3 {

public static void main(String[] args) {

String array[] = {"Hello", "World", "Java", "Oracle", "C-language"}; //String은 reference type. 그래서 각 방에는 번지가 들어간다

for(int i = 0 ; i < array.length ; i++){

System.out.printf("array[%d] = %s\n", i, array[i]);

}

}

}

출력:

array[0] = Hello

array[1] = World

array[2] = Java

array[3] = Oracle

array[4] = C-language

C는 포인터를 이용해 코드짜기는 복잡하지만 메모리를 핸들링 할 수 있지만, 자바는 메모리를 핸들링 할 수 없다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

2차원 배열

/*

2차원배열

1. rectangular array

2. ragged (jagged) array

*/

public class ArrayDemo5 {

public static void main(String[] args) {

/* //rectangular array  - c에서 쓰는 방법

int [][] array;  //1. 선언

array = new int[2][3]; //2. 생성

array[0][0] = 5....; //3. 할당

///////////////////////////////////////////////

int[][] array; //1. 선언

array = new int[][] {{1,2,3},{4,5,6}} ; // 생성 및 할당

///////////////////////////////////////////////

int [][] array = {{1,2,3},{4,5,6},{7,8,9}};  //초기화

*/


//ragged(jagged) array

int [][] array; //1. 선언

array = new int[2][]; //2. 생성

array[0] = new int[4]; //2 - 1. 각 층 생성

array[1] = new int[2]; //행마다 방의 개수를 달리할 수 있다.

array[0][0] = 5; array[0][1] = 6; //3. 할당

//////////////////////////////////////////////////////////////

int [][] array;

array =new int[][]{{1},{3,4,5},{6,7,8,9}}; //2. 생성 및 할당

///////////////////////////////////////////////////////////////

int [][] array ={{1},{2,3},{5,6,7,8}}; //초기화

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

2차원 배열의 사용

public class ArrayDemo6 {

public static void main(String[] args) {

/* int [][] array; //선언

array = new int[2][3];

array[0] = new int[]{1,2,3};

array[1] = new int[]{4,5,6};

*/

int [][] array = {{1,2,3},{4,5,6}}; //위의 4줄을 한번에 써줌.

for(int i = 0 ; i < array.length; i++){

for(int j = 0 ; j < array[i].length; j++){

System.out.printf("array[%d][%d] = %d\t\t\t", i, j, array[i][j]);

}

System.out.println();

}

// array = new int [2][3]; //2차원 배열의 length는 행의 개수

// int [] array = new int[] {1,2,3,4,5}; - 1차원 배열의 length는 방의 개수

// int [][][] array = new int [5][8][9];  - n차원 배열의 length는 맨앞의 숫자. 따라서 이것은 5

// array[0]의 length는 8, array[0][0]의 length는 9. 이런식...

// System.out.println(array.length);

}

}

출력:

array[0][0] = 1 array[0][1] = 2 array[0][2] = 3

array[1][0] = 4 array[1][1] = 5 array[1][2] = 6

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

배열의 각행의 길이가 다를 때

public class ArrayDemo7 {

public static void main(String[] args) {

/*

int [][] array;

array = new int[3][];

array[0] = new int[]{1,2,3};

array[1] = new int[]{4,5,6,7,8,9};

array[2] = new int[]{10}

*/

int [][] array = { //위의 초기화를 간단하게

{1,2,3},

{4,5,6,7,8,9},

{10}

};

for(int i = 0; i < array.length; i++){

for(int j = 0; j< array[i].length; j++){

System.out.printf("array[%d][%d] = %d\t\t\t", i, j, array[i][j]);

}

System.out.println();

}

}

}

출력:

array[0][0] = 1 array[0][1] = 2 array[0][2] = 3

array[1][0] = 4 array[1][1] = 5 array[1][2] = 6 array[1][3] = 7 array[1][4] = 8 array[1][5] = 9

array[2][0] = 10

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

2차원배열을 이용한 함수로 나누어 랜덤값 출력

public class ArrayDemo8 {

public static void main(String[] args) {

int [][] array = input();

output(array);

}

static int [][] input(){

int [][] array = new int[2][3];

for(int i = 0 ; i < array.length ; i++)

for(int j = 0; j < array[i].length ; j++)

array[i][j] = (int)(Math.random() * 10 + 1);

return array;

}

static void output(int [][] array){

for(int i = 0 ; i < array.length ; i++)

for(int j = 0; j < array[i].length ; j++)

System.out.printf("array[%d][%d] = %d\t\t\t", i, j, array[i][j]);

System.out.println();

}

}


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

몇개인지 입력 받고, 숫자들을 입력받은 후 버블정렬로 오름차순.

import java.util.Scanner;


public class ArrayDemo9 {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int num;

System.out.print("몇 개 입력 ? : ");

num = scan.nextInt();

int [] array = new int[num];

for(int i = 0 ; i < array.length ; i++){

array[i] = scan.nextInt();

}

bubbleSort(array);

output(array);

}

static void bubbleSort(int [] array){

for(int i = 0 ; i < array.length-1 ; i++){

for(int j = 0 ; j < array.length-1-i ; j++){

if(array[j] > array[j+1]) swap(array, j, j+1);

}

}

}

static void swap(int [] array, int first, int second){

int temp =  array[first];

array[first]  = array[second];

array[second] = temp;

}

static void output(int [] array){

for(int su : array) System.out.print(su + "\t");

System.out.println();

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

자바에서 1차원 배열의 스왑 -2차원 배열을 사용해야한다.

public class ArrayDemo11 { //배열 두개를 넘겨서 swap하면 c에서 call by value한 것과 같게된다. 그래서 바뀌지 않는 값을 얻게된다.

public static void main(String[] args) {

int [][] array = new int[2][5];  //그래서 스왑을 위해 새로운 2차원배열을 선언한다.

array[0] = new int[]{1,2,3,4,5};

array[1] = new int[]{10,20,30,40,50};

System.out.println("Before Swapping");

print(array);

swap(array);

System.out.println("After Swapping");

print(array);

}

static void print(int [][] array){

for (int i = 0 ; i < array.length ; i++){

for (int j = 0 ; j < array[i].length ; j++){

System.out.printf("%d, ", array[i][j]);

}

System.out.print(" --> " );

}

System.out.println();

}

static void swap(int [][] array){

int [] temp = array[0];

array[0] = array[1];

array[1] = temp;

}

}


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

성적관리 프로그램(성적순으로 정렬)

import java.util.Scanner;

public class ArrayDemo10 {

public static void main(String[] args) {

String [] nameArray = new String[3];

int [][] array = new int[3][4];

input(nameArray, array);

calc(array);

sort(nameArray, array);

output(nameArray, array);

}

static void input(String [] nameArray, int [][] array){

Scanner scan = new Scanner(System.in);

for(int i = 0; i < nameArray.length; i++){

System.out.println((i + 1) + " 번째 학생");

System.out.print("Name : " );

nameArray[i] = scan.next();

System.out.print("국어 : " );

array[i][0] = scan.nextInt();

System.out.print("영어 : " );

array[i][1] = scan.nextInt();

System.out.print("수학 : " );

array[i][2] = scan.nextInt();

}

}

static void calc(int [][] array){

for(int i = 0 ; i < array.length; i ++){

for(int j = 0 ; j < array[i].length -1 ; j++){ //총점을 빼야하므로, -1해줘야함.

array[i][3] += array[i][j];

}

}

}

static void sort(String [] nameArray, int [][] array){

for(int i = 0 ; i < nameArray.length-1 ; i++){

for(int j = 0 ; j < nameArray.length-1-i ; j++){

if(array[j][3] < array[j+1][3]){

String temp = nameArray[j];

nameArray[j] = nameArray[j+1];

nameArray[j+1] = temp;

int [] tempArray = array[j];

array[j] = array[j+1];

array[j+1] = tempArray;

}

}

}

}

static void output(String [] nameArray, int [][] array){

for(int i = 0 ; i < nameArray.length ; i++){

System.out.printf("%s\t\t", nameArray[i]);

for(int j = 0 ; j < array[i].length ; j++){

System.out.printf("%d\t", array[i][j]);

}

System.out.printf("%10.2f\n", array[i][3] / 3.);

}

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

2차원 배열 출력 - 각 층의 주소를 출력함수로 보낸다.

public class ArrayDemo12 {

public static void main(String[] args) {

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

for(int i = 0 ; i < array.length ; i++){

print(array[i]);

}

}

static void print(int [] array){

for(int su : array)

System.out.print(su + "\t");

System.out.println();

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

자바 조심해야할 점

public class ArrayDemo13 {

public static void main(String[] args) {

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

print(array);

}

static void print(int [] array){

for(int i = 0 ; i < 5 ; i++){ //자바는 절대로 숫자를 쓰지않는다. 5가아닌 array.length로 

System.out.print(array[i] + "\t");

}

System.out.println();

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

배열의 주소복사

public class ArrayDemo14 {

public static void main(String[] args) {

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

int [] second = {10,9,8,7,6,5,4,3,2,1};

int [] temp = first;

first = second;

second = temp;

print(first);

print(second);

}

static void print(int [] array){ //배열의 주소 복사는 개수와 상관 없다.

for(int su : array) System. out.print(su + "\t");

System.out.println();

}

}

출력:

10 9 8 7 6 5 4 3 2 1

1 2 3 4 5

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

//배열의 값 복사

public class ArrayDemo15 {

public static void main(String[] args) {

int [] source = {1,2,3,4,5,6,7,8,9,10};

int [] dest = {10,9,8,7,6,5,4,3,2,1};

System.arraycopy(source, 0, dest, 0, source.length);

System.out.printf("source[0] = %d, dest[0] = %d\n", source[0], dest[0]);

source[0] = 10000;

System.out.printf("source[0] = %d, dest[0] = %d\n", source[0], dest[0]);

}

}

출력:

source[0] = 1, dest[0] = 1

source[0] = 10000, dest[0] = 1

----------------------

//배열의 값 복사

public class ArrayDemo15 {

public static void main(String[] args) {

int [] source = {1,2,3,4,5,6,7,8,9,10};

int [] dest = {10,9,8,7,6};

System.arraycopy(source, 0, dest, 0, source.length);  //오류 발생. 값 복사는 숫자가 맞아야한다.

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

자바의 처음 시작인 String[] args

public class ArrayDemo16 {

public static void main(String[] args) {

for(int i = 0 ; i <args.length ; i ++){

System.out.printf("array[%d] = %s\n", i, args[i]);

}

}

}

이렇게 코딩하고, 에디트 플러스의 경우 도스창에서 java ArrayDemo16 딸기 바나나 포도 사과 복숭아 배 레몬 을 입력하면

array[0] = 딸기 ~~~ array[6] = 레몬 까지 출력된다. 클래스명 다음부터 0번지로 인식한다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

간단한 계산기

//java ArrayDemo16에서 4 + 7 을 입력하면 문자로 들어가기때문에 "4" "+" "7"이다.

public class ArrayDemo16 {

public static void main(String[] args) {

int first = Integer.parseInt(args[0]); //"4" --> 4

   int second = Integer.parseInt(args[2]); //"7" --> 7

String op = args[1];

int result =0;

switch(op){

case "+" : result = first + second; break;

case "-"  : result = first - second; break;

case "x"  : result = first * second; break;

case "/"  : result = first / second; break;

case "%" : result = first % second; break;

}

System.out.printf("%d %s %d = %d\n", first, op, second, result);

}

}



Chapter 6. Arrays.pdf


출처 : www.javaexpert.co.kr


ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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


이클립스 설치 

지난번에 다운 받은 리눅스용 이클립스. tar xvfz eclipse-java*.tar.gz

홈폴더에서 예전에 사용하던 C용 이클립스 이름을 mv Eclipse EclipseCDT 바꿔줌.

지금 설치한 이클립스를 mv eclipse ../EclipseJDT 홈폴더로 이동.(홈폴더는 /home/mino임)

그리고 아래 파일을 /usr/share/applications에 넣어주어야한다.

eclipse.desktop

위 파일은 자기의 경로에 맞게 적어주어야 하므로 경로 수정이 필요함.

그리고 터미널에서 옮기기 위해서는 권한이 필요하므로 

sudo mv eclipse.desktop /usr/share/applications/eclipse.desktop  를 써주면 옮겨간다(eclipse.desktop이 있는 폴더에서 작성 해준다)(-경로수정방식은 예전 C이클립스 설치 편에서 설명했었다)

그리고  그 파일을 런쳐로 드래그앤 드랍하면 된다.


이클립스 첫시작 

File-new- JAVA project 선택해서 JRE를 Use default jre(~~) 선택
src 우측버튼 -> new-class 선택. Name : 쓰고 public static void main 체크



Arrays의 사용. 

import java.util.Arrays;

public class ArrayDemo {


public static void main(String[] args) {

int [] array = {4,3,7,2,1,9,2};

System.out.println("Before Sorting");

print(array);

System.out.println("After Sorting");

Arrays.sort(array);

print(array);

}

static void print(int [] array){

for(int su : array) System.out.print(su+"\t");

System.out.println();

}

}

출력:
Before Sorting
4 3 7 2 1 9 2
After Sorting
1 2 2 3 4 7 9

=======================================================
sublime 설치 -- 결과적 실패.. 따라서 설치 안함...

리눅스에서 http://www.sublimetext.com/ 이동. 버전 3의 다운로드 페이지는 http://www.sublimetext.com/3 이다.

Ubuntu 32bit 선택해서 다운. 그리고 터미널에서 다운로드 페이지로 이동 후에 sudo dpkg -i sublime*.deb 엔터.

search에서 sublime 치면 나온다. 편하게 쓰기 위해 런쳐로 이동시켜준다.

다시 인터넷 https://sublime.wbond.net/installation#st3 로 이동.

SUBLIME TEXT3 의 써 있는 내용을 전부 그대로 복사. 그리고 복사한 내용을 sublime에 다시가서 view-show console 창에서 제일 밑에 줄에 글 쓰는 곳에 붙여넣기.

그러면 설치를 해주는데 설치확인은 preference 탭에서 package control이 있다면 설치 완료.

다음은 preference-setting user 로 들어간다. 거기서 {} 안에 

{

"font_face" : "Verdana",

"font_size" : 12,

"line_padding_top" : 2,

"line_padding_bottom" : 2,

"ignored_packages" :

[

"Vintage"

]

}

save하면 바로 적용이 된다.

다음으로 한글패키지 설치를 해보자. ctrl + shift + p 키를 누른다.

package control 검색해서 package control :install package 선택. 그리고 convertToUTF8 을 검색해서 눌러줌.

거기서 File-Set file Encodiing to - Korean 선택.

다시 ctrl + shift + p 눌러서 package control :install package 선택. 그리고 javatar 써줌. 그럼 설치 완료.

view-side bar-show open files 선택.

한번 닫았다가 다시 열어준다.

Tools-Build System-New Build System 선택.

다지우고 아래와 같이 써줌.

{

"cmd": ["javac", "$file_name"],

"working_dir" : "/home/mino/JavaRoom"

}

저장은 file-save as 해서 mino -  .config  -  sublime-text-3   -   packages  -  User 에서 JAVAC.sublime-build 로 저장.

이번엔 run을 설정하기 위해 다시 Tools-Build System-New Build System 선택. 아래와 같이 적어줌.

{

"cmd": ["java", "$file_base_name"],

"working_dir" : "/home/mino/JavaRoom"

}

저장은 file-save as 해서 mino -  .config  -  sublime-text-3   -   packages  -  User 에서 JAVARUN.sublime-build 로 저장.

HelloWorld의 예제를 작성해서 시험해보자. Tools-Build System에서 JAVAC 선택한다. 그리고 Tools-Build 선택. 컴파일완료.

그리고 Tools-Build System에서 JAVA 선택해서 다시 BUILD 하면 실행된다.

---------여기까지하면 subprime 실행 가능. 그러나 밑에 것까지하면 안됨.

컴파일과 런을 실행하는 방법이  복잡하기 때문에 편하게 하기위해 아래파일을 

runJava.sh

/usr/lib/jvm/jdk1.7.0_51/bin/runJava.sh 로 이동시켜준다.

그리고 cd $JAVA_HOME 엔터. 그리고 cd bin 이동. ls -l로 보면 권한이 없는 것을 볼 수있다.

거기서 chmod 755 runJava.sh  로 권한 변경.

HOME 폴더에 show hidden file로 파일보이게 해서 .config 폴더 선택

그리고 sublime-text-3 폴더 - Pacages 폴더 - User폴더 에서 아까만들었던 JAVARUN.sublime-build파일 삭제.

그리고 JAVAC.sublime-build 를 아래와 같이 변경.

{

"cmd": ["/bin/bash","runJava.sh","$file_base_name"],

"working_dir" : "/home/mino/JavaRoom"

}

이름도 변경된 능력에 맞게 JAVA.sublime-build로 변경.

실패함 --- XXXX

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




public class LiteralDemo {

public static void main(String[] args) {

byte num = 5; //byte는 1byte지만 앞의 쓸데 없는 3byte를 짤라서 넣어줌.

byte num1 = 9;

byte sum = num + num1; //자바의 이항연산은 무조건 int 이상.

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

}

}


public class LiteralDemo {

public static void main(String[] args) {

int result = (4 > 2) ? 9 : 9.0; //먼저 결과값인 9와 9.0을 비교해서 오류발생. result를 double로 해줘야함.

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

}

}


public class LiteralDemo {

public static void main(String[] args) {

short a = 1997;

short result = (4 > 2) ? a : 32768; //short는 -32768~32767까지 표현하므로 에러. 만일 32767이라면 출력은 1997이 나옴.

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

}

}

먼저 조건을 바로 비교하는 것이 아니라 뒤에 있는 값을 먼저 비교한다.

----------------------------------

/*

boolean type : %b

*/

public class  BooleanDemo {

public static void main(String[] args) {

boolean b = 4 > 7;  //false

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

System.out.printf("b = %b\n", b);

b = true;

System.out.printf("b = %b\n", b);

}

}

출력 :

b = false

b = false

b = true

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

/*

표준 입력 3가지 방법

1. java.util.Scanner Class    

  이것은 에디트플러스로 작성하면 실행시키기 위해서 도스창으로 나가야한다.

*/

import java.util.Scanner;


public class StandardInputDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);  //stdin

System.out.print("당신의 이름은 ? : "); //scanf와 마찬가지로 중간에 공백이 있으면 안된다.

String name = scan.next(); //scan에서 글씨를 읽어오는 next

System.out.print("당신의 나이는 ? : ");

int age = scan.nextInt();

System.out.print("당신의 키는 ? : ");

double height = scan.nextDouble();

System.out.printf("name = %s, age = %d, height = %.1f\n", name, age, height);

}

}

----------------------------------------

/*

표준 입력 3가지 방법

2. javax.swing.JOptionPane class

  이것은 실행을 하면 그래픽창이 하나 떠서 입력을 받는다.

*/

import javax.swing.JOptionPane;


public class StandardInputDemo1 {

public static void main(String[] args) {

String name = JOptionPane.showInputDialog(null, "당신의 이름은 ? ");

System.out.printf("name = %s\n", name);

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

2진수 출력

public class IntDemo {

public static void main(String[] args) {

//int max = 2147483647;

int max = Integer.MAX_VALUE;

short maxShort = Short.MAX_VALUE;

System.out.printf("max = %d\n", max);

System.out.printf("max = %o\n", max);

System.out.printf("max = %x\n", max);


int kor = 0B11110000_11110000_11110000_11110000;  //2진수로 표현은 0B로 시작.

System.out.printf("kor = %d\n", kor);

System.out.printf("kor = %o\n", kor);

System.out.printf("kor = %x\n", kor);

int eng = Integer.MIN_VALUE; //-2147483648

System.out.printf("eng = %s\n", Integer.toBinaryString(eng)); //2진수로 출력

}

}

출력:

max = 2147483647

max = 17777777777

max = 7fffffff

kor = -252645136

kor = 36074170360

kor = f0f0f0f0

eng = 10000000000000000000000000000000

---------------------------------

글자 5를 숫자5로 형변환 하는 법

public class IntDemo1 {

public static void main(String[] args) {

// int su = (int)"5"; //형변환 불가. 원본이 

String value = "5";

int su = Integer.parseInt(value); //글자 5가 숫자 5로

System.out.printf("su = %d\n", su+10);

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class IntDemo2 {

public static void main(String[] args) {

//literal 과 value를 출력할 때 다른 점

int max = Integer.MAX_VALUE;

System.out.printf("max + 1 = %d\n", ++max);

}

}

출력 : 

max + 1 = -2147483648

literal 로 찍었을 때 : 하지만 System.out.printf("max + 1 = %d\n", 2147483648); 로 했을 때의 값은 같지 않다.

literal 은 변수에 할당된 값.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

얼마나 정확한 값을 찍느냐를 생각하며 float와 double 중 무엇을 쓸지 결정.

public class FloatDemo {

public static void main(String[] args) {

float f = 0.123456789123456789f;

double d = 0.123456789123456789d;

System.out.printf("f = %.18f\n", f);

System.out.printf("d = %.18f\n", d);

}

}

출력:

f = 0.123456791043281560

d = 0.123456789123456780

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

성적 입출력

import javax.swing.JOptionPane;


public class FloatDemo {

public static void main(String[] args) {

int kor, eng, mat, tot;

kor = Integer.parseInt(JOptionPane.showInputDialog(null,"국어점수 : "));

eng = Integer.parseInt(JOptionPane.showInputDialog(null,"영어점수 : "));

mat = Integer.parseInt(JOptionPane.showInputDialog(null,"수학점수 : "));

tot = kor + eng + mat;

double avg = tot / 3.;

String result = "kor = " + kor + ", eng = " + eng + ", mat = " + mat + "\n";

result  += "tot = " + tot + ", avg = " + String.format("%.2f", avg);  //소수점 2자리까지 평균을 나타낸다.

JOptionPane.showMessageDialog(null,result);

System.out.printf("avg = %e\n", avg); //그래픽 입출력 후에 그래픽 창이 닫히면 평균을 출력해줌.

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

값 복사

public class CopyValueDemo {

public static void main(String[] args) {

int su = 5;

int num = su; //value copy

System.out.printf("su = %d, num = %d\n", su, num);

su = 100;

System.out.printf("su = %d, num = %d\n", su, num);

}

}

출력:

su = 5, num = 5

su = 100, num = 5

public class RefCopyDemo {

public static void main(String[] args) {

Demo d = new Demo();

d.age = 25;

Demo d1 = new Demo();

d1.age = d.age; //d.age는 premitive type이므로 값 복사.

System.out.printf("d.age = %d, d1.age = %d\n", d.age, d1.age);

d.age = 100;

System.out.printf("d.age = %d, d1.age = %d\n", d.age, d1.age);

}

}

class Demo{

int age;

}

출력:

d.age = 25, d1.age = 25

d.age = 100, d1.age = 25

-------------------

주소 복사

/*

Pascal Casing : Class, Interface, Enum, StudentDemo  - 첫글자 대문자

Camel Casing : variable, method, su, num, displayDemo(); - 첫글자 소문자, 중간에 단어는 대문자. ()있으면 함수, 없으면 변수.

올대문자는 상수. _로 단어구분.

*/

public class RefCopyDemo1 {

public static void main(String[] args) {

Demo d = new Demo();

d.age  = 25;

Demo d1 = d;

System.out.printf("d.age = %d, d1.age = %d\n", d.age, d1.age);

d.age = 100; //d는 Demo, premitive 타입이 아닌 경우에는 주소복사.

System.out.printf("d.age = %d, d1.age = %d\n", d.age, d1.age);

}

}

class Demo{

int age;

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class LocalVariableDemo {

public static void main(String[] args) {

int su; //지역변수

System.out.println("su = " + su); //반드시 초기화를 해야한다. 아니면 에러가난다.

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class LocalVariableDemo {

public static void main(String[] args) {

int su = 5; 

{

int su = 1000;

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

}

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

}

}

C와는 달리 블록과는 아무 상관 없다. 위에서 int su를 두개를 정의해주어 오류가 발생한다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class LocalVariableDemo {

public static void main(String[] args) {

for(int i = 1; i<= 100 ; i++){}

System.out.printlf("i = " + i);

}

}

오류 발생. for문이 끝나고 지역변수 i는 사라짐.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class MemberVariableDemo {

int eng = 100;  //member variable, instance variable

public static void main(String[] args) {

int kor = 90;   //local variable

System.out.println("eng = " + eng); //오류발생. eng는 메모리에 올라오지도 않았다. 

}

}

--------- 출력을 위해서는 MemberVariableDemo의 집을 지어주어야 한다.

public class MemberVariableDemo {

int eng = 100;  //member variable, instance variable

public static void main(String[] args) {

int kor = 90;   //local variable

MemberVariableDemo mvd = new MemberVariableDemo(); //mvd라는 MemberVariableDemo의 집이 지어졌다.

System.out.println("eng = " + mvd.eng);

}

}

----------------------------

class variable을 출력.

public class ClassVariableDemo {

int kor; //member variable, instance variable //밑에서 선언해 줄 때(집을 지어줄 때) 만들어지고. 언제 없어질지는 모른다.

static int eng = 89;  //static variable, class variable //메인보다 먼저 메모리에 잡힌다. static은 공유 변수. 언제 없어질지는 모른다.

public static void main(String[] args) {

int su; //local variable

//class variable을 출력하기 위해서 세가지 방법이 있다. 어떤 것으로도 출력을 할 수 있다.

// 1. System.out.println("eng = " + eng);

// 2. ClassVariableDemo cvd = new ClassVariableDemo();

// System.out.println("eng = " + cvd.eng);

// 3. System.out.printfln("eng = " + ClassVariableDemo.eng);

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

자바에서 변수를 접근하는 방법은 3가지뿐이다.

public class VariableDemo {

public static void main(String[] args) {

int mat = 70;  //local variable

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

Demo d = new Demo(); //Demo class의 주소를 알아야하기 때문에

System.out.println("kor = " + d.kor);

System.out.println("eng = " + Test.eng);

}

}

class Demo{

int kor = 100; //member variable, instance variable

static int eng = 100;

}

class Test{

static int eng = 80;  //static variable, class variable

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Operator  >>, >>> 차이

public class OpDemo {

public static void main(String[] args) {

int min = Integer.MIN_VALUE;

System.out.printf("min = %d --> ", min);

System.out.println(Integer.toBinaryString(min));

int result = min >> 26; //1로 채움. 

System.out.printf("min >> 26 = %d --> ", result);

System.out.println(Integer.toBinaryString(result));

int result1 = min >>> 26; //0으로 채움. 음수가 양수로

System.out.printf("min >>> = %d --> ", result1);

System.out.println(Integer.toBinaryString(result1));

}

}

출력:

min = -2147483648 --> 10000000000000000000000000000000

min >> 26 = -32 --> 11111111111111111111111111100000

min >>> = 32 --> 100000

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class OpDemo1 {

public static void main(String[] args) {

byte num = 10;

byte result = ~num; //오류발생. 단항 연산자에 ~, +, - 연산자를 쓰면 결과는 integer

byte result = +num;   

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

문자열 비교

import java.util.Scanner;

public class IfDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.print("당신은 어느 계절을 좋아하시나요(영문소문자로) ? : ");

String season = scan.next();

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

if (season.equals ("spring")) System.out.println("개나리, 진달래"); //문자열비교 방법1

else if (season.compareTo("summer") == 0) System.out.println("장미, 아카시아"); //문자열비교 방법 strcmp와 비슷

else if (season.equals("fall")) System.out.println("백합, 코스모스");

else System.out.println("동백, 매화");

}

}

ㅡㅡㅡㅡㅡㅡㅡ자바는 스위치문에서 문자열을 case로 할 수 있다.

import java.util.Scanner;

public class IfDemo {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.print("당신은 어느 계절을 좋아하시나요(영문소문자로) ? : ");

String season = scan.next();

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

switch(season){

case "spring" : System.out.println("개나리, 진달래"); break;

case "summer" : System.out.println("장미, 아카시아"); break;

case "fall" :  System.out.println("백합, 코스모스"); break;

case "winter" : System.out.println("동백, 매화"); break;

default : System.out.println("그런 계절은 없습니다.");

}

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class 스위치데모 { //클래스이름으로 한글도 가능하다.

public static void main(String[] args) { //랜덤값. 최대값을 곱하고 최소값을 더해 int로 형변환

int random = (int)(Math.random() * 10 + 1);

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

switch(random){ //3이 나오면 세 과일, 4가 나오면 두 과일이 나온다. break의 중요성.

case 1 : System.out.println("Bananas"); break;

case 2 : System.out.println("Orange"); break;

case 3 : System.out.println("Peach");

case 4 : System.out.println("Apples");

case 5 : System.out.println("Plums"); break;

case 6 : System.out.println("Pineapples"); break;

case 7 : System.out.println(""); break;

default : System.out.println("Nuts");

}

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class ForDemo {

public static void main(String[] args) {

int [] array = {10,20,30,40,50}; //괄호가 중간에 오는 것을 좋아해. 뒤에 써도 괜찮아.

/* for(int i = 0 ; i < 5 ; i++){

System.out.printf("array[%d] = %d\n", i, array[i]);

}*/ //c의 방법

for(int su : array) //반복변수를 쓰지않음. array속의 들어있는 전부를 찍는다.

System.out.println(su); //이방법의 단점은 1~100 이렇게 찍는 것은 할 수 있다. 배열이거나 콜렉션일 때만사용한다.

}

}

출력:

10

20

30

40

50

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

while문을 이용한 구구단

public class WhileDemo {

public static void main(String[] args) {

int i = 1;

while (i<11)

{

System.out.print(i + "\t\t\t");

int j = 1;

while (j<11)

{

System.out.printf(i*j + "\t");

j++;

}

System.out.println();

i++;

}

}

}

출력:

1 1 2 3 4 5 6 7 8 9 10

2 2 4 6 8 10 12 14 16 18 20

3 3 6 9 12 15 18 21 24 27 30

4 4 8 12 16 20 24 28 32 36 40

5 5 10 15 20 25 30 35 40 45 50

6 6 12 18 24 30 36 42 48 54 60

7 7 14 21 28 35 42 49 56 63 70

8 8 16 24 32 40 48 56 64 72 80

9 9 18 27 36 45 54 63 72 81 90

10 10 20 30 40 50 60 70 80 90 100

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

로또

public class LottoDemo {

public static void main(String[] args) {

int num1, num2, num3, num4, num5, num6;

do{

num1 = (int)(Math.random() * 45 + 1);

num2 = (int)(Math.random() * 45 + 1);

num3 = (int)(Math.random() * 45 + 1);

num4 = (int)(Math.random() * 45 + 1);

num5 = (int)(Math.random() * 45 + 1);

num6 = (int)(Math.random() * 45 + 1);

}while(num1 == num2 || num1 == num3 || num1 == num4 || num1 == num5 || num1 == num6 ||

num2 == num3 || num2 == num4 || num2 == num5 || num2 == num6 ||

num3 == num4 || num3 == num5 || num3 == num6 || 

num4 == num5 || num4 == num6 || 

num5 == num6 );

System.out.printf("%d %d %d %d %d %d\n", num1, num2, num3, num4 , num5, num6);

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ





Chapter 4. Expressions and Operators.pdf


Chapter 5. Control Flow Statement.pdf


출처 : www.javaexpert.co.kr

+ Recent posts