본문 바로가기

공부/자바 OOP

5월23일 - Method 메소드 ★매우 중요★

함수 - 메소드 ★★ 매우 중요

특별한 기능을 가지고 있음

자바 메소드, 자바스크립트 function, 데이터베이스 procedure 같은 함수의미

형식 : 리턴형 함수명( )

함수명의 의미를 파악하고 일정한 기능을 가지고 있는 것처럼 만들어 볼 것이담

maker가 제공하는 함수(쓰려면 클래스를 알아야한다)도 있고 사용자가 정의(user defined)할 수도 있다.

식별자 : 프로젝트명 - basicJava

            팩키지명   - oop0523

            클래스명   - Test01_Method 

            변수명      

            함수

메소드의 위치 :  class와 main 사이 / 맨 밑 main class 괄호 사이

위치 1 
위치 2

함수를 작성할 때 고려사항

1) 매개변수(parameter, 전달값)가 있는지?

   - 변수가 받아서 변수로 전달하는 것 

2) 리턴값(return)이 있는지?

3) 함수정의(작성)를 하고 호출해야 사용할 수 있다.

   - 작성하고 호출안해도 오류아님

   - 작성안하고 호출하면 오류임 

 

함수 호출

main 함수에서 test1함수를 부를수 있다

test1 만 적으면 변수를 호출하는 것이므로 함수 호출이 아니다 

test1 ( ) 괄호를 꼭 적어야 함수가 호출됨 !

 

package oop0523;

public class Test01_Method {

//함수를 작성하는 영역
	
//void 리턴값이 없다 홈런과 같음 	
public static void test1( ) {  //함수정의 
	System.out.println("HEY");
}//test1() end
	
public static void test2( ) {
	System.out.println("I want sleep");
	return; //호출한 곳으로 되돌아감 
		     //마지막 return은 생략가능
}//test2() end
	
public static void main(String[] args) {
			
//함수호출
//test1 변수 
test1(); //함수호출
test1();
		
test2();
test1();
test2();
	
}//main() end	
	//함수를 작성하는 영역	
}//class end

매개변수가 있는 경우

package oop0523;

public class Test02_Method {

	public static void test3( int a ) {  // a는 parameter 매개변수
		System.out.println(a);
	}//test3() end
	
	public static void test4( int a, int b ) {  //지역변수 안에서살아있고 나오면서 없어짐
		                                           //test3에 있는 a와 다른 의미, 스코프가 다름
		System.out.println(a+","+b);
		return; //생략가능
	}//test4() end
	
	public static void test5( double a, char b, String c) {
		System.out.println(a+", "+b+", "+c);
	}//test5() end
	
	public static void main(String[] args) {
		// 메소드
		// 매개변수가 있는 경우
		
		//메소드 호출
		//test3(5); //5는 int a에 a값을 주고 print로 a값을 출력
		//test3(7);
		//test3(9);
		
		//전달값이 2개이상인 경우
		//test4(6, 8);
		//test4(9, 7);
		
		//전달값의 자료형이 다양한 경우
		test5(1.2, 'R', "Korea");
		
		
		
		
	}//main() end
}//class end

 

메소드 연습문제

package oop0523;

public class Test03_Quiz {
	//주석안에 들어있는 것 내가 한것 .
/*
	public static void abs(int a){
		if(a>=0){
			System.out.println(a);
		}else{
			System.out.println(-a);
		}
	}//abs() end
*/	 
	public static void abs(int a){
		if(a<0){
			System.out.println(a+"절대값:"+(-a));
		}else{
			System.out.println(a+"절대값:"+a);
		}//if end
	}//abs() end
	 	
    public static void leap(int y){
		if(y%4==0 && y%100!=0 || y%400==0){
			System.out.println("윤년");
		}else{
			System.out.println("평년");
		}
	}//leap() end

    /*
    public static void fact(int a){
    	int hap=1;
		for(int p=a;p>=1;p--){			
		   	hap=hap*p;	
		}//for end		       
		System.out.println("4!의 값 : "+hap);
    }//fact() end
*/
    public static void fact(int f){
    	long gop=1;
    	for(int a=f;a>=1;a--){
    		gop=gop*a;
    	}//for
    	System.out.println(f+"팩토리얼"+gop);
    }//fact end
    
    /*
    public static void graph(int a, char b){
       for(int p=a;p<=a;p++){
    	   
    	   System.out.println("#");  	   
       }
    }//graph() end
	*/
    public static void graph(int n, char ch){
    	for(int a=1;a<=n;a++){
    		System.out.print(ch);
    	}
    	System.out.println();
    }//graph() end
    
 /*   
    public static void hap(int a, int b){
    	
    }//hap() end
  */
    
    public static void hap(int start, int end){
    	if (start>end){
    		int tmp=start; start=end; end=tmp;
    	}//if end
    	
    	int sum=0;
    	for(int a=start; a<=end; a++){
    		sum=sum+a;
    	}//for end
    	
    	System.out.println(sum);
    }//hap end
    
	public static void main(String[] args) {
		// 메소드 연습문제
		// 문제 1) 절대값을 출력하시오
		abs(-3);
		
		//문제 2) 윤년, 평년을 구분해서 출력하시오
		leap(2019);
		
		//문제 3) 팩토리얼값을 출력하시오
		fact(4); //4*3*2*1
		
		//문제 4) 전달한 수만큼 문자를 출력하시오
		graph(10, '#'); //##########
		
		//문제 5) 두 수 사이의 누적의 합을 출력하시오
		hap(2, 5); //5+2=7
		
		
		
		

	}//main() end
}//class end

리턴값이 있는 경우

package oop0523;

public class Test04_Method {

	public static int test1(int a, int b){
		int sum=a+b;
		return sum; //리턴값은 1개만 가능하다
		                  //리턴값이 있으니 void는 아니다. void 자리에 변수의 자료형을 넣는다.
	}//test1 end
	
    public static boolean leap(int y){
		if(y%4==0 && y%100!=0 || y%400==0){
			return false;
		}else{
			return true;
		}
	}//leap() end
    
    public static char upper(char ch){
    	if(ch>='a' && ch<='z'){
    		return (char)(ch-32);
    	}else{
    		return ch;
    	}
    }//upper end
    
    public static String append(String a, String b){
    	return a+b;
    }//append end
    
    public static int max(int a,int b, int c){
    	int result1=(a>b) ? a : b ;
		int result2=(result1>c) ? result1 : c ;
		return result2 ;
    }//max end
    
	
	public static void main(String[] args) {
		// 리턴값이 있는 경우
		// 함수정의 -> 리턴형 함수명 ( ){ }
		// 리턴값이 없다 : void
		int result=test1(3, 5);
		System.out.println(result);

		result=test1(3,5);
		System.out.println(result);
		
		System.out.println(test1(6,8));
//------------------------------------------------------------------------------------------		
		if(leap(2019)){  //boolean형으로 쓸수도 있다. 반대로 참거짓을 메소드에 주어서 
			                  //리턴시키기
			System.out.println("윤년");
		}else{
			System.out.println("평년");
		}//if end
//------------------------------------------------------------------------------------------		
		//대문자로만 출력하시오
		char ch= upper('r');
		System.out.println(ch);
//------------------------------------------------------------------------------------------		
		String str=append("손","토");
		System.out.println(str);
//------------------------------------------------------------------------------------------		
		//문제 ) 세개의 정수 중에서 최대값을 출력하시오
		int m= max(3,7,9);
		System.out.println("최대값 : "+m);
		
		
		
		
		
	}//main() end
}//class end

전달값이 배열인 경우

package oop0523;

public class Test05_Method {

	public static void test1(int a, int b){
		System.out.println(a+b);
	}//test1 end
	
	public static void test2(int[] a){
		for(int idx=0;idx<a.length ;idx++){
			System.out.println(a[idx]);
		}//for
	}//test2() end
	
	public static void test3(String a,String b){
		System.out.println(a+b);
	}//test3() end
	
	public static void test4(String[] a){
		for(int idx=0;idx<a.length ;idx++){
			System.out.println(a[idx]);
		}//for
	}//test4() end
	
	public static void test5(int a, int b){
		System.out.println(a);
		System.out.println(b);
	}//test5() end
	
	public static void test6(int[][] su){
		int row=su.length ;
		for(int a=0;a<row;a++){
			int col=su[a].length ;
			for(int b=0;b<col;b++){
				System.out.println(su[a][b]);
			}
			System.out.println();
		}//for end
	}//test6() end
	
/*	
	public static void test7(char a, char b){
		System.out.println(a);
		System.out.println(b);
	}//test7() end
*/	
	//내가 한것 
	public static int mo(char [][] em){
		int result=0; 
		int row=em.length ;
		for(int a=0;a<row;a++){
			int col=em[a].length ;
			for(int b=0;b<col;b++){
				char c=em[a][b];
				if(c>='A' && c<='Z'){ //대문자가 있을 경우 소문자로 바꾸어 소문자 케이스로만 비교 
 					c=(char)(c+32);					
				}			
			switch(c){
			case 'a' :
			case 'e' :
			case 'i' :
			case 'o' :
			case 'u' : result ++;
			
				
			}
			}
			}//for
	return result;
	}//mo end

	public static void test7(char a, char b, char c){
		System.out.print(a);
		System.out.print(","+b);
		System.out.print(","+c);
		System.out.println();
	}//test7() end
/*선생님
	public static int mo(char[][] ch){
		int count=0;
		int row=ch.length ;
		for(int a=0; a<row;a++){
			int col=ch[a].length ;
			for(int b=0;b<col;b++){
				switch(ch[a][b]){
				case 'a' :
				case 'e' :
				case 'i' :
				case 'o' :
				case 'u' : count++;
				}//switch end
			}//for end
		}//for end		
	    return count;
	}//mo() end
	*/
	
		
	public static void main(String[] args) {
		// 전달값이 1차원 배열인 경우
		/*
		int[] su={2,4,6};
		test1(su[0],su[2]); // test1(2,6)
		test2(su);
		
		String[] name={"진","무","홍"};
		test3(name[0],name[2]);
		test4(name);
        */
//--------------------------------------------------------------------------------		
		//전달값이 2차원 배열인 경우
		int[][] su={
				        {1,2,3},
				        {6,5,4}
		               };
		test5(su[0][0],su[1][2]);
		test6(su);
		
		char[][] ch={
				          {'Y','e','a','r'},
				          {'M','o','n','t','h'},
				          {'A','a','t','e'}
		                 };
		test7(ch[0][0],ch[1][0],ch[2][0]);
		
		//문제 ) 모음의 갯수를 출력하시오
	    int result=mo(ch);
	    System.out.println("모음의 갯수는 "+result);
	
	}//main() end
}//class end

 

코딩정리하기

프로젝트클래스(basicjava) 우클릭 ->refresh /validate

project-> clean

 

메소드

매개변수(parameter)가 있는 경우

->전달값 argument value

 

 

Math 클래스

method summary

함수이름 (매개변수 )

-math 클래스의 여러 함수들 ,

//절대값
System.out.println(Math.abs(-3));      //3
//올림
System.out.println(Math.ceil(1.3));     //2.0
//버림
System.out.println(Math.floor(2.7));    //2.0
//반올림
System.out.println(Math.round(3.8));  //4

//큰값
System.out.println(Math.max(7, 9)); //9
//작은값
System.out.println(Math.min(7, 9));  7
		
System.out.println(Math.max(7, Math.max(5, 6))); //7

 

random 무작위 

난수 :  random 값

random 함수 중요

발생 범위 : 0.0<=r<1.0

//System.out.println(Math.random()); //1보다 작은값
		//System.out.println(Math.random()*2); //1보다 큰값이 나올수도 잇웅
		//System.out.println((int)(Math.random()*3)); //0 1 2
		//System.out.println((int)(Math.random()*4)); //0 1 2 3
		

예제) 주사위

//문제 ) 주사위 수의 범위 : 1~6
		//0이 나오면 안됨, *6을 했을 때 0,1,2,3,4,5 까지 나오므로 +1을 해주면 
		//1,2,3,4,5,6 이 나오게 된다.		
		//System.out.println((int)(Math.random()*6)+1);

예제) 로또 

//문제 ) 로또번호 범위 : 1~45
		System.out.println((int)(Math.random()*45)+1);
		System.out.println((int)(Math.random()*45)+1);
		System.out.println((int)(Math.random()*45)+1);
		System.out.println((int)(Math.random()*45)+1);
		System.out.println((int)(Math.random()*45)+1);
		System.out.println((int)(Math.random()*45)+1);

 

'공부 > 자바 OOP' 카테고리의 다른 글

5월29일 - Class  (0) 2019.05.29
5월28일 - 메소드 + 정렬  (0) 2019.05.28
5월 22일 - 배열 2+연습문제  (0) 2019.05.22
5월 21일 - 배열 1  (0) 2019.05.21
5월 21일 - while/ do~while 반복문+ 도형 + 연습문제  (0) 2019.05.21