1. 자바의 IO 

- 데이터를 읽어 오거나 출력에 관련된 작업

- 스트림: 자바는 데이터를 입출력할때 스트림(Stream)을 사용한다. 스트림은 데이터의 흐름이다.

- 스트림은 근원지(Source)와 목적지(Destination)가 존재한다.(단방향, 한방향으로 이동)

- 스트림의 종류

  1) 바이트단위로 구분
     - 1바이트 스트림 : 1바이트 단위로 처리, ~InputStream, ~OutputStream
     - 2바이트 스트림 : 2바이트 단위로 처리(문자처리 때문에 만들어짐)
                           ~Reader, ~Writer

  2) 입출력으로 구분
     - 입력 스트림 : 읽어오는 기능 ~InputStream, ~Reader
     - 출력 스트림 : 출력하는 기능 ~OutputStream,~Writer
       
  3) 기능으로 구분
     - NodeStream   : 가장 기본적인 스트림 InputStream, OutputStream
     - BridgeStream : 1바이트스트림을 2바이트스트림으로 변환
     - FilterStream : NodeStream에 여러 편리한 기능을 덧붙인 스트림


ex> InputStream 
import java.io.InputStream;
import java.io.IOException;
public class Test01_NodeStream
{
    public static void main(String[] args)
    {
        //키보드와 연결된 입력 스트림객체 얻어오기
        InputStream in=System.in;

        try{
            System.out.println("글자 딱 하나만 입력하세요!");

            //public abstract int read()  throws IOException
            //키보드로 읽어온 데이터를 바이트단위로 얻어오기
            int n=in.read();
            System.out.println("입력된글자:" + (char)n);
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }
    }
}



ex> InputStreamReader

package test01.node;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class Test02_Reader
{
    public static void main(String[] args)
    {
        //InputStreamReader(InputStream in) 
        InputStream in=System.in;
        Reader rd=new InputStreamReader(in);
        System.out.println("딱 하나의 문자만 입력");

        try
        {
            //public int read()   throws IOException
            int n=rd.read();
            System.out.println("입력된 글자:" +(char)n);
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }        
    }
}



ex> 표준출력장치 (모니터--> System.out)과 연결된 출력객체 얻어오기

package test01.node;
import java.io.IOException;
import java.io.OutputStream;

public class Test03_OutputStream
{
    public static void main(String[] args)
    {
        //표준출력장치(모니터==>System.out)과 연결된 출력객체 얻어오기
       OutputStream out=System.out;

        int a=65;

        try{
            out.write(a);
            //버퍼가 다차지 않아도 강제로 데이터를 내보내라(출력해라!)
            //out.flush();
            //void write(byte[] b)
            byte []b={65,66,67,68};
            out.write(b);
            
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }finally{
            try{
                out.close();//스트림닫기(수도꼭지잠그기)
            }catch(IOException ie){
                System.out.println(ie.getMessage());
            }
        }
    }
}



ex> OutputStreamWriter
package test01.node;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.io.OutputStreamWriter;

public class Test04_Writer
{
    public static void main(String[] args)
    {
        //OutputStreamWriter(OutputStream out) 
        //화면과 연결된 출력스트림객체 얻어오기
        OutputStream out=System.out;

        //화면으로 데이터를 출력하기위한 2바이트 출력스트림 생성하기
        Writer wt=new OutputStreamWriter(out);

        //void write(char[] cbuf)  
        char ch[]={'한','글','사','랑'};

        try{
            //char배열 화면에 출력하기
            wt.write(ch);
            wt.write("아리랑 아리랑");
            //스트림닫기
            wt.close();
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }
    }
}



ex>  FileWriter    파일에 데이터를 출력하기 위한 2바이트 처리 스트림 클래스
package test01.node;
import java.io.FileWriter;
import java.io.IOException;

public class Test05_FileWriter
{
    public static void main(String[] args)
    {
        FileWriter fw=null;

        try
        {
            //test.txt파일에 2바이트단위로 데이터를 출력하기위한 스트림 생성
            //fw=new FileWriter("test.txt");
            //new FileWriter("출력할파일명",추가모드로 열건지);
            //test.txt파일이 존재하면 파일뒤에 데이터가 추가됨
            fw=new FileWriter("test.txt",true);

            //문자열을 파일로 출력(저장하기)
            fw.write("안녕하세요!\r\n");
            fw.write("제이름은 이길동입니다.\r\n");
            fw.write("밥 먹으러 가요~!\r\n");

            System.out.println("파일로 저장 성공!");
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }finally{
            try{
                if(fw!=null) fw.close();
            }catch(IOException ie){
                System.out.println(ie.getMessage());
            }
        }
    }
}


ex>FileReader
package test01.node;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Test06_FileReader
{
    public static void main(String[] args)
    {
        FileReader fr=null;

        try
        {
            //test.txt파일에서 2바이트단위로 데이터를 읽어오기위한 스트림객체생성
           fr=new FileReader("test.txt");

            while(true)
            {
                //파일에서 글자하나(2바이트) 읽어오기.스트림의끝(파일끝)에
                //도달하면 read메소드는 -1을 반환한다.
                int n=fr.read();
                if(n==-1) break;//파일끝이면 반복문 끝내기

                //파일에서 읽어온 글자를 화면에 출력하기
                System.out.print((char)n);
            }
        }catch(FileNotFoundException fe){
            System.out.println(fe.getMessage());
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }finally{
            try{
                if(fr!=null) fr.close();
            }catch(IOException ie){
                System.out.println(ie.getMessage());
            }
        }
    }
}
 


ex> FileOutputStream
package test01.node;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test07_FileOutputStream
{
    public static void main(String[] args) {

        FileOutputStream fos=null;

        try
        {
            //파일에서 데이터를 읽어오기위한 1바이트 처리 스트림생성
           fos=new FileOutputStream("data.dat");
        
            //public void write(byte[] b,int off,int len) throws IOException
            byte []b={65,66,67,68,69,70};

            //b배열 0번째부터 3개를 파일로 저장하기
            fos.write(b,0,3);

            String str="hello";
            fos.write(str.getBytes());

            fos.close();
            System.out.println("파일로 저장 성공!");
        }catch(FileNotFoundException fe){
            System.out.println(fe.getMessage());
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }
    }
}
 

package test01.node;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Test08_FileInputStream
{
    public static void main(String[] args)
    {
        FileInputStream fis=null;

        try
        {
            //파일에서 데이터를 읽어오기위한 1바이트 처리 스트림객체 생성
           fis=new FileInputStream("data.dat");
            
            //while(true){
            //    //파일에서 1바이트 읽어오기
            //   int n=fis.read();
            //    //파일끝이면 빠져나가기
            //    if(n==-1) break;
            //    //읽어온 데이터 화면에 출력하기
            //    System.out.print((char)n);
            //}

            byte[] b=new byte[1024];

            while(true)
            {
                //파일에서 읽어와 b배열에 저장,n에는 읽어온 바이트수크기가 저장됨
                int n=fis.read(b);

                if(n==-1) break;//파일끝이면 빠져나가기

                //배열을 문자열객체로 변환하기
                String str=new String(b);

                //화면에 출력하기
                System.out.println(str);
            }
            fis.close();//스트림 닫기

        }catch(FileNotFoundException fe){
            System.out.println(fe.getMessage());
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }
    }
}
 
 
 
ex> 키보드로 5명의 이름과 전화번호를 입력받고 입력받은 데이터를 파일로 저장해보세요
package test01.node;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Quiz01
{
    public static void main(String[] args)
    {
        //파일에 저장하기 위한 스트림객체
        FileWriter fw=null;

        //파일에서 읽어오기 위한 스트림객체
        FileReader fr=null;

        //키보드로 입력받기 위한 객체
        Scanner scan=new Scanner(System.in);

        try
        {
            //파일에 저장하기 위한 2바이트 처리스트림객체 생성
            fw=new FileWriter("phone.txt");

            //키보드로 다섯명 데이터 입력받아 파일로 저장하기
            for(int i=1;i<=2;i++)
            {
                //키보드로 입력받기
                System.out.println("이름입력");
                String name=scan.next();

                System.out.println("전화입력");
                String phone=scan.next();

                //파일로 저장하기
                fw.write(name+"," +phone +"\r\n");
            }

            System.out.println("파일로 저장성공!");

            fw.close();//스트림닫기
            
            //파일에서 읽어오기 위한 2바이트 처리 스트림객체
            fr=new FileReader("phone.txt");

            //--while(true){
            //    int n=fr.read();
            //    if(n==-1) break;
            //    System.out.print((char)n);
            //}--

            int n=0;
            while((n=fr.read())!=-1){
                System.out.print((char)n);
            }

            fr.close();

        }catch(FileNotFoundException fe){
            System.out.println("해당 파일이 존재하지 않아요!");
        }catch(IOException fe){
            System.out.println(fe.getMessage());
        }
    }
}
 
 
 
ex>  파일복사하는 프로그램을 작성해 보세요.
 예)
 원본파일명:aa.txt  ( aa.txt 만 만들어 놓은 상태에서 실행하면 copy.txt 파일이 만들어 진다. )
 복사본파일명:copy.txt
 ==>aa.txt파일을 copy.txt파일로 복사 (1바이트 처리스트림 사용해서)

package test01.node;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Quiz02
{
    public static void main(String[] args)
    {
        FileInputStream fis=null;
        FileOutputStream fos=null;

        try
        {
            //원본파일을 읽어오기위한 스트림객체
            fis=new FileInputStream("aa.txt");

            //복사본파일에 출력하기위한 스트림객체
            fos=new FileOutputStream("copy.txt");

            byte []b=new byte[1024];
            long fileSize=0;

            while(true)
            {
                //파일에서 데이터 읽어와 b배열에 저장
                //n에는 읽어온 바이트수크기가 저장됨
                int n=fis.read(b);

                if(n==-1) break;

                //b배열의 0번째 위치부터 n개만큼만 파일로 저장
                fos.write(b,0,n);

                //파일크기 구하기
                fileSize+=n;            
            }

            System.out.println(fileSize + "bytes 크기의 파일복사성공!");
            //스트림닫기
            fos.close();
            fis.close();
        
            // 1BYTE씩 읽기.
            //--    while(true){
            //    //원본파일에서 1바이트 읽어오기
            //    int n=fis.read();
            //    if(n==-1) break;//파일끝이면 반복문 끝내기
            //    //복사본파일에 1바이트 출력하기
            //    fos.write(n);
            //}
            //System.out.println("파일복사성공!");
            //스트림닫기
            //fos.close();fis.close();
            //--/
            
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }
    }
}
 

 
ex>  phone.txt 파일을 BufferedReader객체를 이용해서 한줄씩 읽어와 화면에 출력해 보세요.

package test01.node;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class Quiz03
{
    public static void main(String[] args)
    {
        //   InputStream in=new FileInputStream("phone.txt");
        //Reader rd=new InputStreamReader(in);
        //BufferedReader br=new BufferedReader(rd);
        //

        try
        {
            Reader rd=new FileReader("phone.txt");
            BufferedReader br=new BufferedReader(rd);

            //--    while(true){
            //    String line=br.readLine();
            //    if(line==null) break;
            //    System.out.println(line);
            //}--

            String line=null;
            while((line=br.readLine())!=null){
                System.out.println(line);
            }
            br.close();
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }
    }
}



 

 

'JAVA' 카테고리의 다른 글

File 클래스  (0) 2014.09.12
자바 IO ( Ⅱ )  (0) 2014.09.12
예외처리 ( Exception )  (0) 2014.09.12
Calendar 클래스  (0) 2014.09.12
자료구조 - ArrayList / 제네릭 클래스 / 확정for 문  (0) 2014.09.12

 

1. 예외 (Exception)처리 



- 예외 : 프로그램 실행도중에 예기치 못하게 발생되는 경미한 에러


- 예외처리 : 예외가 발생되었을때 이에 대한 적절한 처리를 하는것


- 형식


try{

     예외가 발생될수 있는 실행문장;

      ...

} catch(예외타입1 참조변수){

      예외가 발생되었을때의 적절한 처리문장;

      ....

}finally{

      예외와 상관없이 무조건 수행해야 할 문장;

       ...

}

==> 예외가 발생될수 있는 문장을 try{}블록으로 묶고 catch 절에서 예외가 발생되었을때 해당하는 적절한 처리를 한다.



ex>

package test01.exception;

import java.util.Scanner;


public class Test01{

    public static void main(String[] args){


        Scanner scan = new Scanner(System.in);

        

        while(true){


            System.out.println("첫번째 수 입력(종료:0)");

            int a=scan.nextInt();


            if(a==0){

                break;

            }


            System.out.println("두번째 수 입력");

            int b=scan.nextInt();


            try{

                int c=a/b;

                System.out.println(a+"/"+b+"="+c);

            }catch(ArithmeticException e){

                System.out.println("오류메시지:" + e.getMessage());

                System.out.println("0으로 나눌수 없습니다.");

                continue;

            }            

        }

    }

}



ex>

package test01.exception;

import java.util.InputMismatchException;

import java.util.Scanner;


public class Test02{


    public static void main(String[] args){


        Scanner scan = new Scanner(System.in);

        System.out.println("1st:");


        try{

            int n1=scan.nextInt();

            System.out.println("2st:");

            int n2=scan.nextInt();

            int n3=n1/n2;

            System.out.println("나누기한 값 "+ n3);

        }catch(InputMismatchException ie){

            System.out.println("숫자만 입력하세요.");

        }catch(ArithmeticException ae){

            System.out.println("0으로 나눌수 없습니다.");

        }


        System.out.println("Exit!!");

    }

}




자바의 모든 예외는 Exception의 자식클래스이므로 Exception은 모든 예외를 처리할 수 있다.

catch절에서 Excepion은 모든 예외를 처리할수는 있으나 자식예외보다 먼저 위치할 수는 없다.

ex>

package test01.exception;

import java.util.InputMismatchException;

import java.util.Scanner;


public class Test03{


    private static Scanner scan;


    public static void main(String[] args) {

        scan = new Scanner(System.in);

        System.out.println("1st:");

        try{

            int n1=scan.nextInt();

            System.out.println("2st:");

            int n2=scan.nextInt();

            int n3=n1/n2;

            System.out.println("나누기한 값 "+ n3);

        // 모든 예외는 Exception타입으로 처리할수 있다.

        }catch(InputMismatchException e){

            System.out.println("숫자만 입력합니다.");

        }catch(Exception ie){

        // 부모예외가 반드시 아래에 와야 함.!!

            System.out.println(ie.getMessage());

        }

        System.out.println("Exit!!");

    }

}





2. Exception의 종류


 - 자바에는 두가지 종류의 익셉션이 있다.


 1) Checked Exception


 - RuntimeException을 상속받지 않은 예외클래스


 - 반드시 try~catch절로 예외처리를 해야 하며 예외처리를 하지 않으면 컴파일시에 오류를 발생시킨다.

 예) IOException, FileNoFoundException,...



 2) UnChecked Exception


 - RuntimeException을 상속받은 예외클래스


 - try~catch절로 예외처리를 하지 않아도 컴파일시에 오류가 발생되지 않으며 프로그래머가 선택적으로 try~catch로 처리한다.

 예) NumberFormatException, ArithmeticException,...




EX>

package test01.exception;

import java.io.*;


public class Test04{


    public static void main(String[] args){


        //String a="10  00";

        //int n=Integer.parseInt(a);

        

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("keyboard로 부터 숫자를 입력받다.");

        

        //keyboard로 부터 한줄 입력받

        try{

            String num=br.readLine();

            int n1=Integer.parseInt(num);

            System.out.println(num);

        }catch(IOException ie){

            System.out.println(ie.getMessage());

        }catch(NumberFormatException e){

            System.out.println("숫자만");

        }

    }

}





3. 예외처리방법


 - 자바에서는 예외처리방법이 두가지가 있다.


 방법1) 예외가 발생될수 있는 문장을try~catch로 직접 처리


 방법2) 자신이 직접 처리하지 않고 throws로 예외를 떠넘기는 방법이 있다.

  throws로 떠넘길때는 이를 호출하는 곳에서 try~catch로 처리해야 한다.



ex> 방법 1 예외가 발생될수 있는 문장을try~catch로 직접 처리

package test01.exception;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;


public class Test05{


    public static void main(String[] args){


        String name=input("이름입력");

        System.out.println(name);


        String phone=input("전화번호입력");

        System.out.println(phone);

    }


    public static String input(String msg){


        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println(msg);

        String str="";

        

        try{

            str=br.readLine();

            return str;

        }catch(IOException ie){

            System.out.println(ie.getMessage());

            return null;

        }finally{

            System.out.println("finally");

        }

    }

}



ex> 방법 2 throws로 예외를 떠넘기는 방법

package test01.exception;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;


public class Test06{


    public static void main(String[] args){


       try{

            String name;

            

            name =input("이름입력");            

            System.out.println(name);


            String phone=input("전화번호입력");

            System.out.println(phone);


       }catch(IOException ie){

            System.out.println(ie.getMessage());

        }

    }

    

    // 자신이 처리하지 않고 throws로 예외를 넘김.--> 메소드를 호출한 곳에서 try~catch로 처리한다.

    public static String input(String msg)throws IOException

    {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println(msg);

        String str="";

        str=br.readLine();

        return str;

    }

}





ex> 값 2개 입력받아 나눗셈 실행하기.

package test01.exception;

import java.util.Scanner;


public class Test07{


    public static void main(String[] args){


        Scanner scan = new Scanner(System.in);

        

        System.out.println("1st :");

        int n1=scan.nextInt();


        System.out.println("2st :");

        int n2=scan.nextInt();

        

        try{

            int n3=div(n1,n2);

            System.out.println("나눗셈 한 값 :" + n3);

        }catch(ArithmeticException ae){

            System.out.println("0으로 나눌수 없습니다.");

        }finally{

            System.out.println("무조건 실행");

        }

        System.out.println("Exit!!");

    }

    public static int div(int n1, int n2) throws ArithmeticException{

        int n3=n1/n2;

        return n3;

    }

}





4. 예외를 강제로 발생시키기


 문법적인 오류는 아니더라도 논리적으로 오류가 있을때 예외를 강제로 발생시킬수 있다.


 형식> throw 예외객체;

 


EX> 가로,세로 값으로 넓이 구하기. 강제 예외  발생

package test01.exception;

public class Test08{


    public static void main(String[] args){


        //사각형 가로,세로

        int x=100,y=-200;


        try{

            //사각형넓이 구하기

            int rectArea = area(x,y);

            System.out.println("사각형 넓이:" + rectArea);

        }catch(Exception e){

            System.out.println(e.getMessage());

        }

    }


    public static int area(int x, int y) throws Exception

    {

        //Exception e=new Exception("가로,세로는 0보다 커야 한다.");

        

        // 논리적으로 잘못된 값이 들어오면

        if(x<=0 || y<=0){

            //강제로 예외객체 발생.

            throw new Exception("가로,세로는 0보다 커야 한다.");

        }

        int z=x*y;

        return z;

    }

}




ex> 사용자 예외처리 클래스

package test01.exception;


class RectException extends Exception

{

    public RectException(String msg)

    {

        super(msg);

    }

}


public class Test09

{

    public static void main(String[] args)

    {

        // TODO Auto-generated method stub

        int a=10, b=-10;

        

        try{

            // 논리적으로 잘못된값이 들어온 경우

            if(a<=0 || b<=0){

                //사용자가 만든 예외객체 생성해서 던지기

                throw new RectException("가로,세로 길이는 0보다 크게");

            }

        }catch(RectException re){

            System.out.println(re.getMessage());

            return;

        }

        

        int area=a*b;

        System.out.println("넓이:" + area);

    }

}




 

 

'JAVA' 카테고리의 다른 글

자바 IO ( Ⅱ )  (0) 2014.09.12
자바 IO - Stream ( Ⅰ )  (0) 2014.09.12
Calendar 클래스  (0) 2014.09.12
자료구조 - ArrayList / 제네릭 클래스 / 확정for 문  (0) 2014.09.12
자료구조 - Map  (0) 2014.09.12

 

1. Calendar 클래스


- 날짜와 시간에 대한 정보를 갖는 클래스


- 추상클래스이므로 객체를 생성할 수는 없고 자식클래스를 이용하거나 getInstance메소드를 통해 내부적으로 생성된 Calendar객체를 얻어와 사용


 예)

 // 내부적으로 생성된 현재시각에 대한 정보를 갖는 Calendar객체 얻어오기

 Calendar cal=Calendar.getInstance();

 


import java.util.Calendar;

public class Test01_Calendar {


    public static void main(String[] args) {


        //public static Calendar getInstance()

        //현재시각에 대한 정보는 갖는 날짜 객체 얻어오기

        Calendar cal=Calendar.getInstance();

        

        //2012년 2월 1일에 대한 정보로 설정

        cal.set(2012,1,1);

        

        //System.out.println(cal);


        //public int get()


        //현재 년도 얻어오기

        int y=cal.get(Calendar.YEAR);


        //월얻어오기(1월은 0값을 갖음)

        int m=cal.get(Calendar.MONTH)+1;


        //날짜 얻어오기

        int d=cal.get(Calendar.DATE);

        System.out.println(y +"년 " + m +"월 " + d +"일");


        //요일에 해당하는 숫자값을 얻어옴(일요일:1 ~ 토요일:7)

        int w=cal.get(Calendar.DAY_OF_WEEK);

        String str="";

        switch(w){

            case Calendar.SUNDAY    :

                str="일요일";break;

            case Calendar.MONDAY    :

                str="월요일";break;

            case Calendar.TUESDAY    :

                str="화요일";break;

            case Calendar.WEDNESDAY :

                str="수요일";break;

            case Calendar.THURSDAY:

                 str="목요일";break;

            case Calendar.FRIDAY:

                str="금요일";break;

            case Calendar.SATURDAY:

                str="토요일";break;

        }

        System.out.println("오늘은 " + str +"입니다.");


        //현재시간을 출력해 보세요. xx시 xx분 xx초

        Calendar cal1=Calendar.getInstance();

        int h=cal1.get(Calendar.HOUR_OF_DAY);

        int mi=cal1.get(Calendar.MINUTE);

        int s=cal1.get(Calendar.SECOND);


        System.out.println("현재시간:" + h+"시" + mi+"분" + s+"초");

        

        //public int getActualMaximum(int field)

        //field중에서 가장 큰값 얻어오는 메소드

        int mm=cal1.getActualMaximum(Calendar.MONTH);

        System.out.println("month중 가장 큰값:" + mm);


        //해당월 중에 가장 큰 날짜(day)얻어오기

        int day=cal1.getActualMaximum(Calendar.DAY_OF_MONTH);

        System.out.println("이번달은 " + day +" 까지 있어요!");

    }

}





2. GregorianCalendar  


ex> GregorianCalendar사용하여 윤년인지 아닌지 확인

package test01.aa;

import java.util.Calendar;

import java.util.GregorianCalendar;


public class Test02_GregorianCalendar

{

    public static void main(String[] args)

    {

        

          //2011년 2월1일에 대한 정보를 갖는 날짜객체 생성

        GregorianCalendar cal = new GregorianCalendar(2011,1,1);


        int y=cal.get(Calendar.YEAR);

        int m=cal.get(Calendar.MONTH) + 1;

        int d=cal.get(Calendar.DATE);

        System.out.println(y + "년 " + m + "월 "+ d + "일 ");

        

        // 윤년인지 아닌지 얻어옴.(true,false)

        boolean b=cal.isLeapYear(y);

        if(b){

            System.out.println("윤년입니다.");

        }else{

            System.out.println("윤년이 아닙니다.");

        }

    }

}



 

 

'JAVA' 카테고리의 다른 글

자바 IO - Stream ( Ⅰ )  (0) 2014.09.12
예외처리 ( Exception )  (0) 2014.09.12
자료구조 - ArrayList / 제네릭 클래스 / 확정for 문  (0) 2014.09.12
자료구조 - Map  (0) 2014.09.12
자료구조 - Stack / TreeSet  (0) 2014.09.12

 

1. ArrayList(Collection<? extends E> c) 


- Collection<? extends E> c : E타입의 클래스이거나 E타입을 상속받은 자식클래스가 제네릭타입으로 지정됨


- Collection<? super E> c : E타입의 클래스이거나 E타입의 부모클래스가 제네릭타입으로 지정됨



ex>

package test01.util;

import java.util.ArrayList;


class AA{

    private int a;


    public AA(int a){

        this.a=a;

    }

    public int getA(){

        return a;

    }

}

class BB extends AA{


    private int b;


    public BB(int a,int b){

        super(a);

        this.b=b;

    }

    public int getB(){

        return b;

    }

}

public class Test06_generic{


    public static void main(String[] args)

    {

        ArrayList<BB> list1=new ArrayList<BB>();


        list1.add(new BB(1,2));

        list1.add(new BB(3,4));

        list1.add(new BB(5,6));

        

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

        //list.add(new AA(1));

        

        //list1은 AA의 자식클래스들을 담고 있으므로 가능!

        ArrayList<AA> list2=new ArrayList<AA>(list1);

        

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

            AA aa=list2.get(i);

            System.out.println(aa.getA());

        }

    }

}

 






2.  제네릭 클래스


- 특정 자료형에 상관없이 똑같은 알고리즘이 적용되는 클래스인 경우 제네릭 클래스로 만들수 있다.



EX>

package test01.util;

class Data<T>{

    private T a;

    public void setA(T a){

        this.a=a;

    }

    public T getA(){

        return a;

    }

}

public class Test07_generic{


    public static void main(String[] args)

    {

        Data<Integer> d1=new Data<Integer>();

        d1.setA(10);

        System.out.println(d1.getA());

        

        Data<String> d2=new Data<String>();

        d2.setA("아리랑");

        System.out.println(d2.getA());

    }

}

 






3. 확장for문


- jdk5.0버전 이상부터 지원됨


- 형식)

    for(저장변수:컬렉션객체 또는 배열)

    {

        반복실행문장;

        ...

    }



EX>

package test01.util;

import java.util.ArrayList;


public class Test08_for{


    public static void main(String[] args)

    {

        int []a={10,20,30,40,50};


        //배열a의 요소가 순차적으로 k에 저장됨

        for(int k:a){

            System.out.print(k +" ");

        }

        System.out.println();


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

        list.add("하나");

        list.add("둘");

        list.add("세엣");

        list.add("네엣");


        for(String str:list)

        {

            System.out.print(str + " ");

        }

        System.out.println();

        

        ArrayList<Member> list1=new ArrayList<Member>();


        list1.add(new Member("song","1234","song@naver.com"));

        list1.add(new Member("kim","0000","kim@naver.com"));

        list1.add(new Member("lee","1111","lee@naver.com"));


        //확장for이용해서 list1의 데이터를 출력해 보세요.

        for(Member mm:list1)

        {

            System.out.println("아이디:" + mm.getId());

            System.out.println("비밀번호:" + mm.getPwd());

            System.out.println("이메일:" + mm.getEmail());

        }

    }

}




 

 

'JAVA' 카테고리의 다른 글

예외처리 ( Exception )  (0) 2014.09.12
Calendar 클래스  (0) 2014.09.12
자료구조 - Map  (0) 2014.09.12
자료구조 - Stack / TreeSet  (0) 2014.09.12
자료구조 API - Collection 프레임워크  (0) 2014.09.12

 

3. Map(**)


- 데이터를 저장할때 key와 value가 한쌍으로 저장되는 자료구조


- key값은 중복될 수 없으며 value는 중복이 가능하다.


- 데이터 검색시 유용하다.



ex>

package test01.util;

import java.util.HashMap;

public class Test03_Map

{

    public static void main(String[] args)

    {

        //key타입은 Integer,value타입은 String을 갖는 HashMap생성

        HashMap<Integer,String> map=new HashMap<Integer,String>();


        //Map에 값을 저장할때는 put메소드를 사용해 key와 value를 한쌍으로 저장한다.

        //V put(K key, V value)  

        map.put(1,"홍길동");

        map.put(2,"유관순");

        map.put(3,"김유신");


        //public V get(Object key)

        //키값(2)에 해당하는 value(유관순)을 얻어옴

        String aa=map.get(2);

        System.out.println(aa);

    }

}

 

 

 

ex> Map

package test01.util;

public class Person

{

    private String name;

    private String phone;


    public Person(String name,String phone)

    {

        this.name=name;

        this.phone=phone;

    }

    public String getName()

    {

        return name;

    }

    public String getPhone()

    {

        return phone;

    }

}


package test01.util;

import java.util.HashMap;

import java.util.Scanner;

public class Test04_Map

{

    public static void main(String[] args)

    {

        Person per1=new Person("홍길동","010-111-1234");

        Person per2=new Person("홍길서","010-222-5678");

        Person per3=new Person("홍길남","010-333-0987");    


        //key값은 String,value값은 Person객체를 갖는 Map객체 생성

        HashMap<String,Person> map=new HashMap<String,Person>();


        //이름을 key값으로 Person객체를 value값으로 Map추가

        map.put(per1.getName(),per1);

        map.put(per2.getName(),per2);

        map.put(per3.getName(),per3);


        System.out.println("찾을 이름 입력");

        Scanner scan=new Scanner(System.in);

        String find=scan.next();


        //find를 key로 사용해서 검색하기


        Person per=map.get(find);

        if(per!=null){

            System.out.println("이름:"+per.getName() +",전화번호:" + per.getPhone());

        }else{

            System.out.println("해당 정보가 존재하지 않아요!");

        }

    }

}



 

ex> Map

package test01.util;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

public class Test05_Map

{

    public static void main(String[] args)

    {

        Map<Integer,String> map=new HashMap<Integer, String>();


        map.put(1,"홍길동");

        map.put(2,"홍길서");

        map.put(3,"홍길남");

        map.put(4,"홍길북");


        //Map의 key값은 중복을 허용하지 않음


        //데이터가 수정됨

        map.put(4,"홀길동");


        String value=map.get(4);


        //key값이 4인 요소 삭제

        map.remove(4);


        //public Set<K> keySet()

        //map.keySet(): map에 담긴 key값을 Set에 담아서 리턴

        Set<Integer> st=map.keySet();


        //Iterator<E> iterator()  

        //Set에 담긴 요소(key값들)을 꺼내오기 위한 Iterator얻어오기

        Iterator<Integer> it=st.iterator();


        //다음요소가 있으면 true

        while(it.hasNext())

        {

            //다음요소(key값) 꺼내오기

            Integer key=it.next();


            //key에 대응되는 Value 꺼내오기

            String val=map.get(key);


            System.out.println(val);

        }

    }

}




 

+ Recent posts