1.  사용자 정의 메소드


 - 형식

 

 리턴형 메소드명(매개변수,...){

       실행문장;

       ...

    [return]

}

 

- 자주 반복되는 작업이나 하나의 작업을 여러개의 작업으로 쪼갤때 메소드를 만든다.



ex> 덧셈메소드 호출하여 사용.

class  Test01_Method

{

    public static void main(String[] args)

    {

        int a=10,b=20;

        int c=sum(a,b);

        System.out.println("두수합:"+c);

    }

    public static int sum(int a,int b)

    {

        int z=a+b;

        return z;

    }

}


ex> 출력 메소드 사용

class Test02_Method

{

    public static void main(String[] args)

    {

        String str="*";

        //str을 10번 출력하는 메소드

        printString(str,10);

        System.out.println("메인메소드 종료!");

    }

    public static void printString(String str,int n)

    {

        for(int i=1;i<=n;i++){

            System.out.print(str);

        }

        System.out.println();

    }

}

 

 

 


 

2. 객체 지향 프로그래밍 

 

- 모든 작업을 객체화해서 프로그래밍하는 기법

- 객체지향 프로그래밍에서는 모든 작업을 클래스로 구현한다.

- 클래스 만드는 형식

 

class 클래스명{

    멤버변수;

      ...

    멤버메소드;

      ...

}

 

 - 클래스를 사용하기 위해서는 객체를 생성해야 한다.

 

   형식 )   클래스명 객체명=new 클래스명();

 


ex>   사각형 클래스 만들기

 - 속성(멤버변수) :  x,y좌표,가로길이,세로길이,선색상,...

 - 기능(멤버메소드) :  사각형을 그리기,사각형을 칠하기,사각형크기변경,..

 

class Rect

{

    //private는 멤버를 외부(자신의 클래스를 제외한 영역)에서 접근 불가!!

    private int x,y;    //좌표

    private int w,h;    //가로세로길이

    private String color;    //선색상


    

    //public 멤버는 어디서든 접근 가능!

    public void drawRect()

    {  //사각형 그리는 기능

        System.out.println(x+","+y+"좌표에 " + 

                w +"," + h +"의 길이로"+

                color+"색상의 사각형을 그립니다.");

     }

    public void setXY(int x1,int y1)

    {    //좌표설정 메소드

         x=x1;  

         y=y1;

    }

    public void setWH(int w,int h)

    {    //가로세로길이 설정 메소드

        if(w<=0 || h<=0){

            System.out.println("가로 세로 길이가 잘못 되었어요!");

            return;

        }

        this.w=w;  this.h=h;

    }

    

    public void setColor(String color)

    {  //선색상 설정 메소드

        this.color=color;

    }

}

class  Test03_Class

{

    public static void main(String[] args)

    {

        //객체(인스턴스) 생성

        Rect rr=new Rect();

        rr.setXY(100,100);

        rr.setWH(100,300);

        rr.setColor("빨강");

  

       // rr.w=-100;

       // rr.h=100;

        rr.drawRect();

    }

}

 

 

 

 


ex> 성적처리 클래스를 만들어 보자.

- 속성 : 학생번호,국어,영어,총점,평균

- 메소드: 값저장,성적계산,데이터출력

 

import java.util.Scanner;

class Student

{

    // 멤버변수 선언(멤버변수는 private로!!! )

    private int num;

    private int kor;

    private int eng;

    private int tot;

    private double ave;


    //값을 저장하는 메소드

    public void input()

    {

        Scanner scan=new Scanner(System.in);

        System.out.println("학생번호");

        num=scan.nextInt();

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

        kor=scan.nextInt();

        System.out.println("영어점수");

        eng=scan.nextInt();

    }

    //성적을 계산

    public void calc()

    {

        tot=kor+eng;

        ave=tot/2.0;

    }

    //데이터를 출력

     public void printData()

    {

        System.out.println("번호:"+num);

        System.out.println("국어:"+kor);

        System.out.println("영어:"+eng);

        System.out.println("총점:"+tot);

        System.out.println("평균:"+ave);

    }

}

class Test04_Class

{

    public static void main(String[] args)

    {

        //Student 객체 생성

        Student stu=new Student();

        stu.input();

        stu.calc();

        stu.printData();

    }

}

 

 

 

 

 

ex>  도서제목,가격,판매부수를 매개변수로 받아 멤버에 값을 저장하는 생성자를 갖는 클래스를 만들고 main에서 사용해 보세요.

 

class MyBook

{

    private String title;

    private int price;

    private int cnt;

    private int total;

 

    //디폴트생성자

    public MyBook(){}

    

    public MyBook(String title,int price,int cnt)

    {

        this.title=title;

        this.price=price;

        this.cnt=cnt;

    }

 

    public void setData(String title,int price,int cnt)

    {

        this.title=title;

        this.price=price;

        this.cnt=cnt;

    }

    public void getTotal()

    {

        total=price*cnt;

    }

    public void printBook()

    {

        getTotal();

        System.out.println("도서제목:"+title);

        System.out.println("판매가격:"+price);

        System.out.println("판매부수:"+cnt);

        System.out.println("총판매가격:"+total +"원");

    }

}


class Quiz05

{

    public static void main(String[] args)

    {

        MyBook bb=new MyBook("자바가 제일 쉬웠어요!",10000,10);

    

        //도서제목,가격,판매부수,총판매가격이 출력됨

        bb.printBook();

 

        MyBook bb1=new MyBook();

        // MyBook() dault 생성자

        bb1.setData("Jsp",10000,5);

        bb1.printBook();

    }

}

 

 

 



3. 생성자(Constructor)


- 객체가 생성될 때 (자동)으로 호출되는 메소드

- 일반적으로 멤버변수값을 초기화하려는 목적으로 만듬.


- 만드는 형식>

클래스명과 동일한 이름으로 만들고 리턴값이 없으며 void 는 쓰지 않는다.


 예)

 class AA{

      int a;

      public AA(){//생성자

       ..

      }

}

 

 

ex>  Font객체를 생성하고 값저장후 출력해 보세요.

(글꼴에 대한 정보를 갖는 클래스)

class Font

{

    //글꼴크기

    private int fontSize;

    //글꼴체

    private String fontName;

    

    //생성자

    public Font()

    {

        fontSize=9;

        fontName="바탕체";

    }

    //파라미터를 갖는 생성자 

    public Font(int size,String name)

    {

         fontSize=size;

         fontName=name;

    }

    //값설정 메소드

    public void setData(int fontSize,String fontName)

    {

         this.fontSize=fontSize;

         this.fontName=fontName;

     }

    //설정값 출력 메소드

    public void printInfo()

    {

         System.out.println("현재설정된 글꼴크기:"+fontSize);

         System.out.println("현재설정된 글꼴체:"+fontName);

         System.out.println();

    }

}

class  Test05_Class

{

    public static void main(String[] args)

    {

        //파라미터가 없는 생성자 호출

        Font ff=new Font();

        ff.printInfo();

        ff.setData(10,"굴림체");

        ff.printInfo();

  

        //파라미터가 있는 생성자 호출

        Font ff1=new Font(18,"궁서체");

        ff1.printInfo();

    }

}

 

 


 

 

'JAVA' 카테고리의 다른 글

final  (0) 2014.09.12
Overloading  (0) 2014.09.12
배열( array )  (0) 2014.09.12
반복제어문( while문 )  (0) 2014.09.12
반복제어문( for문 )  (0) 2014.09.12

 

[ 배열 ]

 

- 같은 자료형의 변수가 여러개 필요한 경우 연속적인 공간에 데이터를 나열해서 저장하고 첨자로 구분하는 자료구조

 

1) 1차원배열

- 첨자가 하나인 경우

- 형식

 자료형 []배열명=new 자료형[크기]

 

 - 예) int []a=new int[5]; //정수가 다섯개 저장될 배열 생성

 


2) 2차원배열

- 첨자가 두개인 경우

- 형식

자료형 [][]배열명=new 자료형[행첨자][열첨자]


- 예)

int [][]a=new int[3][4];//정수가 저장될 공간이 3행 4열로 12개가 생성

   a[0][0]=100;

   a[0][1]=90;

   ...



ex> 배열 선언 후 값 값넣기 / 출력 후 초기화 / 합구하기 

class  MyTest01_Array

{

     public static void main(String[] args)

    {

          //정수가 저장될 공간(배열)이 다섯개 만들어짐

          int []a=new int[5];

          a[0]=100;

          a[1]=80;

          a[2]=70;

          a[3]=50;

          a[4]=90;


          //배열에 저장된 데이터 출력하기

          for(int i=0;i<5;i++)

         {

               System.out.print(a[i]+" ");

          }

          System.out.println();


          //배열은 아래처럼 초기화가 가능하다.

          int []b={100,80,50,60,60,30,40,50,100};

          int sum=0;


          //배열합 구하기

          System.out.println("배열크기:"+b.length);

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

          {

               sum=sum+b[i];//sum+=b[i];

               System.out.print(b[i]+" ");

          }

          System.out.println("배열합:"+sum);

     }

}



ex> 배열값 중 최고값, 최소값 구하기

class MyTest02_Array

{

     public static void main(String[] args)

    {

          int a[]={88,99,100,90,50};

          System.out.println("저장된 배열 요소 값");

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

          {

               System.out.print(a[i]+" ");

          }

          System.out.println();


          int max=a[0];


          //배열의 요소중 가장 큰 값 구하기

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

          {

               if(a[i]>max){

                    max=a[i];

               }

          }

          System.out.println("배열 최대값:"+max);


          //배열의 최소값을 구해 보세요.

          int min=a[0];


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

          {

               if(a[i]<min){

                    min=a[i];

               }

          }

          System.out.println("배열 최소값:"+min);

     }

}



ex> 키보드로 입력받은 데이터 배열에 저장하고 출력하기

import java.util.Scanner;

class MyTest03_Array

{

     public static void main(String[] args)

     {

          Scanner scan=new Scanner(System.in);

          int []a=new int[10];

          System.out.println("10명의 점수 입력");

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

          {

               a[i]=scan.nextInt();

          }

          System.out.println("입력된 점수");

          

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

          {

                System.out.print(a[i]+" ");

          }

          // 점수가 80점 이상인 학생의 수를 구해 보세요.

          int cnt=0;

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

          {

               if(a[i]>=80){

                    cnt++;

               }

          }

          System.out.println("\n80점 이상인 학생수:"+cnt);

     }

}



ex>배열을 오름차순 정렬하기

class MyTest04_Sort

{

     public static void main(String[] args)

     {

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

          int tmp=0;

          for(int i=0;i<4;i++)

          {

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

               {

                    if(a[i]>a[j]){

                         tmp=a[i];

                         a[i]=a[j];

                         a[j]=tmp;

                    }

               }

          }

          System.out.println("오름차순 정렬후");

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

               System.out.print(a[i]+" ");

          }

     }

}



ex> 2차원배열

class MyTest05_Array

{

     public static void main(String[] args)

     {

          int[][]a={

                {1,2,3},

                {4,5,6},

                {7,8,9}

          };

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

               for(int j=0;j<3;j++){

                    System.out.print(a[i][j]+" ");

               }

          }

          System.out.println();

     }

}



ex> 다섯명 아이디 입력받은 후 배열에 저장하고 출력하기 

import java.util.Scanner;


class MyTest06_StringArray

{

    public static void main(String[] args)

    {

        Scanner scan=new Scanner(System.in);

        //문자열 5개가 저장될 배열선언

        String []ids=new String[5];

        System.out.println("다섯명의 아이디를 입력하세요");

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

             ids[i]=scan.next();

        }


        System.out.println("배열에 저장된 아이디");

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

             System.out.println(ids[i]);

        }


        //문자배열에 값 초기화 하기

        String name[]={"홍길동","김철수","김영희"};

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

             System.out.println(name[i]);

        }

    }

}



ex> 2차원 문자배열

회원의 이름을 입력받아 회원의 주소를 출력해 보세요.

(이름은 중복되지 않는다고 가정)

예)

회원이름:홍길동

홍길동 님의 주소 [서울] 입니다.

 

import java.util.Scanner;

class MyTest07_Array

{

    public static void main(String[] args)

    {

        String [][]mem={

            {"홍길동","서울시 송파구.."},

            {"김아무","대전시 ..."},

            {"김유신","부산시 ..."}

        };

          

        Scanner scan=new Scanner(System.in);

          

        System.out.println("주소를 검색할 회원이름 입력");

        String name=scan.next();

        boolean find=false;

        for(int i=0;i<3;i++)

        {

            if(mem[i][0].equals(name))

            {

                System.out.println(name +" 님의 주소는 ["+  mem[i][1] +"]입니다.");

                find=true;

                break;

            }

        }

        //이름을 찾지 못했을때

        if(!find){ 

            System.out.println(name +" 회원님이 존재하지 않아요!");

        } 

    }

}

 

 

 

'JAVA' 카테고리의 다른 글

Overloading  (0) 2014.09.12
클래스( class )  (0) 2014.09.12
반복제어문( while문 )  (0) 2014.09.12
반복제어문( for문 )  (0) 2014.09.12
switch문  (0) 2014.09.12

 

[ while문 ]


 형식)

 

while(조건식){

      반복실행할 문장;

  ...

 }

 ==> 조건이 거짓이 될때까지 반복해서 문장을 수행함

 


 

ex> while문 사용해서 1부터100까지 합 구하기

class MyTest02_while{

    public static void main(String[] args) {

        int sum=0,i=1;

        while(i<=100){

            sum+=i;

            i++;

        }

        System.out.println("1부터100까지 합:"+sum);

    }

}

 



[ 다중 while문 ]

 

 - 형식

 

while(조건식){

     while(조건식){

         반복실행할 문장;

           ...

    }

}

 

 

ex> 값을 입력받아 ( 2~9 사이값) 구구단을 출력한다.

import java.utill.Scanner;


class  MyTest03{

    public static void main(String[] args)  {

        Scanner scan=new Scanner(System.in);

        int i=1;

        while(true){

            System.out.println("단입력(종료:0)");

            int dan=scan.nextInt();

            if(dan==0) break;

            if(dan>9 || dan<2){

                System.out.println("2에서 9사이의 수 입력");

                continue;//초기의 조건식으로 분기

            }

            i=1;

            while(i<=9){

                System.out.println(dan+"*"+i+"="+dan*i);

                i++;

            }

        }

    }

}


 

 

 

 


 

[ do~while ]


- 형식

 

do{

      반복실행할 문장;

  ..

 }while(조건식);

 

==> 조건이 거짓일때까지 반복적으로 수행한다.



ex> 1 ~100까지 합구하기 / 2~9 사이 값 입력 받아 구구단 출력하기 를 do while사용하기

import java.util.Scanner;

class MyTest04_doWhile{

     public static void main(String[] args){

 

          //예1 do~while사용해서 1부터 100까지 합구하기

          int sum=0,i=1;

 

          do{

               sum+=i;

               i++;

          }while(i<=100);

 

          System.out.println("1부터100까지합:"+sum);

 

          //예2 단입력받아 구구단 출력

          Scanner scan=new Scanner(System.in);

 

          int dan=0;

 

          do{

               System.out.println("단입력(2에서9사이 수 입력)");

               dan=scan.nextInt();

           }while(!(dan>=2 && dan<=9));

 

          System.out.println("["+dan+"단]");

 

          for(int j=1;j<=9;j++){

               System.out.println(dan + "*"+ j + "=" + dan*j);

          }

     }

}

 



ex> 난수를 발생시키는 객체 생성하기

import java.util.Random;

 

class MyTest05_Random{

      public static void main(String[] args)  {


          //난수를 발생시키는 객체 생성하기

          Random rnd=new Random();

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

               int n=rnd.nextInt(10);//0부터 9까지의 난수 발생하기

               System.out.println("발생된 난수:" + n);

          }

     }

}

 

 

 

'JAVA' 카테고리의 다른 글

클래스( class )  (0) 2014.09.12
배열( array )  (0) 2014.09.12
반복제어문( for문 )  (0) 2014.09.12
switch문  (0) 2014.09.12
IF문  (0) 2014.09.12

 

[반복제어문]


1. for문



형식1)


 for(초기식;조건식;증감식){

    반복 수행할 문장;

 }

--> 조건이 만족하지 않을때까지 반복적으로 문장을 수행한다.

 

 


 형식2)


for(초기식;조건식;증감식){

     for(초기식;조건식;증감식){

       반복 수행할 문장;

      }

 }

 


ex>

class MyTest12_for

{

    public static void main(String[] args) 

    {

        int i;

        //for사용해서 1부터 100까지 출력하기

        for(i=1;i<=100;i++){

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

        }

        //홀수출력

        System.out.println();

        for(i=1;i<=100;i+=2){

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

        }

        System.out.println();

        //1부터 100까지 합 구하기

        int sum=0;

        for(i=1;i<=100;i++){

            //sum=sum+i;

            sum+=i; 

        }

        System.out.println("1부터 100까지합:"+sum);

        //1부터100까지 수중 짝수합,홀수합을 구해보세요.

        int sum1=0;

        for(i=1;i<=100;i+=2){

            //sum=sum+i;

            sum1+=i; 

        }

        System.out.println("1부터 100까지 홀수합:"+sum1);

        int sum2=0;

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

            //sum=sum+i;

            sum2+=i; 

        }

        System.out.println("1부터 100까지 짝수합:"+sum2);

        sum1=0;sum2=0;

        for(i=1;i<=100;i++){

            if(i%2==1){

                sum1+=i;

            }else{

                sum2+=i;

            }

        }

        System.out.println("홀수합:" + sum1 +",짝수합:"+sum2);

    }

}

 

 

ex>  1부터 50까지 수중 3의 배수를 출력하고 3의 배수합도 출력하세요.


 3 6 9 .... 48

 3의 배수합:xxx

 

class MyTest13_for

{

    public static void main(String[] args) {

        int sum=0;

        for(int i=3;i<=50;i+=3){

            //3의 배수 출력

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

            sum+=i;//3의 배수합 구하기

        }

        System.out.println("\n3의 배수합:"+sum);

    }

}

 

 


형식2)


for(초기식;조건식;증감식){

    for(초기식;조건식;증감식){

        반복 수행할 문장;

    }

}


ex>

class MyTest01_for{

    public static void main(String[] args){

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

            for(int j=1;j<=i;j++){

                System.out.print("*");

            }

            System.out.println();

        }

    }

}

 



 

'JAVA' 카테고리의 다른 글

배열( array )  (0) 2014.09.12
반복제어문( while문 )  (0) 2014.09.12
switch문  (0) 2014.09.12
IF문  (0) 2014.09.12
관계/논리/대입/쉬프트 연산자  (0) 2014.09.12


[ switch ]


- 일치되는 값을 찾아 선택적으로 문장 수행


- 형식

switch(변수 또는 수식){

    case 비교값1:수행할 문장;break;

    case 비교값2:수행할 문장;break;

    case 비교값3:수행할 문장;break;

    ...

    default: 일치되는 값이 없을때 수행할 문장;

   }


주의> case 절에 비교되는 값은 정수형상수 또는  String 만이 올수 있다.(조건절 X,실수 X)

    (double 으로 테스트 해보면 이와같은 에러가 난다. : 

   Cannot switch on a value of type double. Only convertible int values, strings or  enum variables are permitted )


 

ex>

import java.util.Scanner;

class MyTest11_switch

{

    public static void main(String[] args) 

    {

        Scanner scan=new Scanner(System.in);

        System.out.println("상품번호입력");

        int n=scan.nextInt();

        switch(n){

            case 1:System.out.println("축하합니다! 상품 : TV");

            case 2:System.out.println("축하합니다! 상품 : 컴퓨터");

            case 3:System.out.println("축하합니다! 상품 : 스마트폰");break;

            case 4:System.out.println("축하합니다! 상품 : 카메라");break;

            default:System.out.println("상품이 없습니다.");

        }

        char ch='A';

        switch(ch){

            case 'A':System.out.println("축하합니다! 상품 : TV1");break;

            case 'B':System.out.println("축하합니다! 상품 : 컴퓨터1");break;

            case 'C':System.out.println("축하합니다! 상품 : 스마트폰1");break;

            case 'D':System.out.println("축하합니다! 상품 : 카메라1");break;

            default:System.out.println("상품이 없습니다.");

        }

    }

}

 


case 를 여러개 가져갈 경우는 


...

case 1:

case 2:

case 3:

      System.out.println(...);

case 4:

      System.out.println(...);


...


이와 같이 사용하면 된다.




 

 

'JAVA' 카테고리의 다른 글

반복제어문( while문 )  (0) 2014.09.12
반복제어문( for문 )  (0) 2014.09.12
IF문  (0) 2014.09.12
관계/논리/대입/쉬프트 연산자  (0) 2014.09.12
연산자  (0) 2014.09.12

+ Recent posts