class Test7 {
	// 접근제어 리턴타입 메소드명(매개변수타입 매개변수명)
	// 매개변수는 지역변수로 메소드안에서만 사용 가능
	public int sum(int n) { 
    // 매개변수 : (위에서 변수를 받기 때문에 자료형이 더 커야함
    // 1~부터 n까지의 합
		int s=0; // 지역변수. 메소드안에서만 사용가능
		for(int i=1; i<=n; i++) {
			s+=i;
		}
		return s; // 반환값을 가지고 호출한 곳으로 돌아감.
	}
	 // 짝수인지 판별하는 메소드
	public boolean isEven(int n) { // 리턴타입이 있을 경우 리턴을 써야함!	
		return n%2==0;
	}

	// 매개변수로 주어진 문자가 소문자이면 대문자로 변환하는 메소드
	public char upper(char c) {
		return c>='a' && c<='z' ? (char)(c-32) : c;
	}
	
	// 매개변수로 주어진 문자가 소문자이면 true, 그렇지 않으면 false
	public boolean isLower(char c) {
	return c>='a' && c<='z' ;
	}
	
	// 두개의 매개변수로 주어진 정수중 큰 수를 반환하는 메소드
	public int max(int x, int y) {
		return x>y? x : y;
	}
	
	// 매개변수로 주어진 구구단 출력. 단 주어진 매개변수가 1~9사이의 수가 아니면 아무것도 출력하지 않음.
	// void 리턴 타입 : 메소드를 실행하고 호출한 곳으로 값을 반환 할 필요가 없을 때 사용
	// void 리턴 타입인 경우에는 return; 처럼 마지막에 return문을 기술하지만 생략가능
	public void gugudan(int dan) {
		if(dan<1 || dan>9) {
			return; // return을 만나면 메소드는 실행을 멈추고 호출한 곳으로 복귀
		}
		for(int i=1; i<=9; i++) {
			System.out.printf("%d * %d = %2d\n", dan, i, dan*i);
		}
		return; // void에서는 생략 가능 
	}
	
	// 점수에 따른 평점 계산
	// 95~100ㅣ4.5, 90~94:4.0 ... 59~0 : 0.0
	public double grade(int score) {
		double s = 0.0;
		
		if(score>=95) s=4.5;
		else if(score>=90) s=4.0;
		else if(score>=85) s=3.5;
		else if(score>=80) s=3.0;
		else if(score>=75) s=2.5;
		else if(score>=70) s=2.0;
		else if(score>=65) s=1.5;
		else if(score>=60) s=1.0;
		else s = 0.0;
		
		return s;
	}
	
	
}

원래 하나의 클래스에는 하나의 기능만을 넣어야 한다. 단일책임의 원칙 ( 응집도를 높이기 위함)

이번 포스팅에서는 method의 예를 보기위해 여러개의 기능을 같이 넣었다. 

(실제 코딩시에는 이렇게 하면 안된다!!)

 

public class Ex07_method {
	public static void main(String[] args) {
		Test7 tt = new Test7();
		int result;
		
		result = tt.sum(10);
		System.out.println(result);
		
		result = tt.sum(100);
		System.out.println(result);
		
		boolean b;
		b = tt.isEven(13);
		System.out.println(b);
		
		char c;
		c = tt.upper('a');
		System.out.println(c);
		
		c = tt.upper('9');
		System.out.println(c);
		
		result = tt.max(5,  10);
		System.out.println(result);
		
		tt.gugudan(7);
		
		double g = tt.grade(85);
		System.out.println(g);
		
	}
}

'쌍용강북교육센터 > 7월' 카테고리의 다른 글

0714_Ex02_method  (0) 2021.07.14
0714_Ex01_field  (0) 2021.07.14
0713_Ex06_class  (0) 2021.07.14
0713_Ex05_class : 레퍼런스 변수 선언 및 메모리 할당  (0) 2021.07.14
0713_Ex04_class : 클래스에 대해 알아보기  (0) 2021.07.14

+ Recent posts