2. 메소드
by mini_min◾ 메소드는 기능을 구현한다.
접근 제어자 / 리턴 타입 / 메소드명 (매개변수 타입 매개변수) { }
매개변수는 지역 변수라 메소드 안에서만 사용이 가능하고 스택 메모리 영역에 메모리가 할당된다.
지역변수와 매개변수는 메소드를 호출할 때 메모리가 할당되고 메소드를 빠져 나갈 때 소멸된다.
class Test1 {
public int sum(int n) {
int s = 0; // 지역변수 (스택 메모리영역에 메모리 할당
for(int i=0; i<=n; i++) {
s += i;
}
return s; // 반환값을 가지고 호출한 곳으로 돌아감
}
}
public static void main(String[] args) {
Test1 obj = new Test1();
int a;
a = obj.sum(10);
System.out.println(a);
}
◾ 큰 수 판별 / 짝수합 / 짝수 여부 / 대문자 반환 / 점수 평점 / 학점 등
메소드 활용해서 값 반환하기
public class Ex02 {
public static void main(String[] args) {
Test2 t = new Test2();
int s;
char c1, c2;
boolean b;
double g;
String str;
s = t.max(10, 5);
System.out.println("10과 5중 큰 수 : " + s);
s = t.even(100);
System.out.println("1~100사이의 짝수의 합 : " + s);
b = t.isEven(10);
System.out.println("10 짝수 여부 : " + b);
c1 = 'j';
c2 = t.upper(c1);
System.out.println("대문자 변환 : " + c2);
System.out.println();
t.gugudan(5);
System.out.println();
g = t.grade(88);
System.out.println("점수에 대한 평점 : " + g);
str = t.hakjeom(88);
System.out.println("학점 : " + str);
System.out.println(t.random100());
}
}
class Test2 {
/**
* 두 정수 중 큰 값을 반환하는 메소드
* @param a 정수
* @param b 정수
* @return 두 정수 중 큰 값
*/
public int max(int a, int b) {
int n = a > b ? a : b;
return n;
}
/**
* 짝수의 합을 구하는 메소드
* @param n 짝수의 합을 구할 수
* @return 1~n 까지의 짝수의 합
*/
public int even(int n) {
int s = 0;
for(int i=2; i<=n; i+=2) {
s+= i;
}
return s;
}
/**
* 정수가 짝수인지 아닌지 판별하는 메소드
* @param n 판별할 정수
* @return 짝수여부
*/
public boolean isEven(int n) {
return n%2 == 0;
}
/**
* 문자가 소문자인 경우 대문자로 변환하여 반환
* @param c 대문자로 변환할 문자
* @return 변환된 문자
*/
public char upper(char c) {
if(c>='a' && c<='z')
c -= 32;
return c;
// c>='a' && c<='z' ? (char)(c-32) : c;
}
/**
* 인수로 주어진 문저가 대문자이면 true 값을 반환하기
* @param c 대문자인지 판별할 문자
* @return 대문자 여부(true/flase)
*/
public boolean isUpper(char c) {
return c>='A' && c<='Z';
}
/**
* 인수로 넘겨 받은 구구단 출력
* @param n 구구단을 출력할 단.
* 만약, n이 1보다 적거나 9보다 크면 아무것도 출력하지 않는다.
*/
public void gugudan(int n) {
int s = 0;
if(n<1 || n>9) {
return ;
}else {
for(int i=1; i<=9; i++) {
s = n * i;
System.out.printf("%d * %d = %d", n, i, s);
System.out.println();
}
}
}
/**
* 점수에 대한 평점을 계산하여 반환하는 메소드
* 95~100:4.5
* 90~94: 4.0
* 85~89: 3.5
* 80~84: 3.0
* 75~79: 2.5
* 70~74: 2.0
* 65~69: 1.5
* 60~64: 1.0 나머지 : 0점
*
* 점수는 오류가 없다는 가정
* @param score 평점을 계산할 점수
* @return 평점
*/
public double grade(int score) {
double n;
if(score>94) n = 4.5;
else if(score>89) n =4.0;
else if(score>84) n =3.5;
else if(score>79) n =3.0;
else if(score>74) n =2.5;
else if(score>69) n =2.0;
else if(score>64) n =1.5;
else if(score>63) n =1.0;
else n = 0.0;
return n;
}
/**
* 점수에 따른 학점 구하기(90~100:A, 80~89:B, 70~79:C, 60~69:D 나머지 F)
* @param score 학점 계산할 점수
* @return 계산된 학점
*/
public String hakjeom(int score) {
if(score>=90) return "A";
else if(score>=80) return "B";
else if(score>=70) return "C";
else if(score>=60) return "D";
else
return "F";
// String 은 변수 없이 다이렉트로 출력가능.
// switch(score/10) {
// case 10:
// case 9 : s = "A" break; 이렇게 반복 쭉...
}
/**
* 1~100 사이 난수를 발행하여 반환
* @return 난수
*/
public int random100() {
return (int)(Math.random()*100) + 1;
}
}
◾ 메소드 : 배열 값의 합 구하기
public int total(int[] num) { //배열 값의 합 구하기
int s = 0;
for(int i=0; i<num.length; i++) {
s += num[i];
}
return s;
}
int [] n = {2,4,6,8,10};
int s;
Test4 obj = new Test4();
s = obj.total(n);
System.out.println(s);
◾ 메소드 : 랜덤 배열 주소(값) 참조 하기
public int[] random(int n) { //랜덤 발생한 배열 주소(값) 추출
if(n<1)
return null;
int[]a = new int[n];
for(int i=0; i<a.length; i++) {
a[i] = (int)(Math.random()*100) + 1;
}
return a; //1개 이상 리턴 못하지만, 배열을 이용하면 여러 값 가능
//리턴타입에 배열을 넣으면 배열의 주소 1개(+여러값) 출력 가능
}
int[] num = obj.random(10);
for(int a : num) {
System.out.println(a + " ");
}
◾ call by value : 형식매개변수와 실매개변수가 기억공간을 따로 확보한다.
◾ call by reference : 참조(주소)값을 전달한다.
참조 주소 값을 받아서, 그 참조 주소 값에 더하기를 한다.
참조 주소 값이 원래는 10이었는데 sub() 를 호출해서 참조 주소 값 10에 10이 더해지고 20이 출력되었다.
class Test5 {
int x = 10;
// call by value
public void sub1(int a) {
a += 10; //a=5를 받아 메소드 값은 15가 됐지만 메인 a 는 그대로 5
}
// call by reference
public void sub2(Test5 obj) { //가로속에 클래스 처음 써봄
//주소(참조) 값을 받음. 참조값에 더하기
obj.x += 10;
}
//넘긴 nn이 배열이니까 매개변수도 배열이 와야한다.
public void sub3(int []n) { //주소(참조)값을 받음 참조값 값에 더하기
n[1] += 10;
}
}
Test5 t = new Test5();
int a = 5;
t.sub1(a);
System.out.println("sub1() 호출 후 a : " + a);
// call by value : 형식매개변수와 실매개변수가 기억공간을 따로 확보
// 기본 자료형은 파라미터 전달방법이 call by value 이다.
System.out.println("sub() 호출 전 x : " + t.x); //10
// call by reference : 참조(주소)값을 전달
// 객체를 파라미터로 전달하는 경우 파라미터를 call by reference
t.sub2(t);
System.out.println("sub() 호출 후 x : " + t.x); //20
int []nn = {1, 3, 5, 7, 9};
System.out.println("sub3() 호출 전 nn[1] : " + nn[1]);
t.sub3(nn);
System.out.println("sub3() 호출 전 nn[1] : " + nn[1]);
}
◾ 재귀 호출 : 자기 자신을 불러내는 것도 가능하다.
public class Ex06_recursion {
public static void main(String[] args) {
Test6 obj = new Test6();
obj.write(5);
System.out.println();
}
}
class Test6 {
public void write(int n) {
if (n>1) write(n-1); //자기가 자기를 불러버린 것
//일단 스택에 '5'를 저장하고 n-1 실행
System.out.printf("%3d ", n);
}
}
◾ 재귀 호출로 합 구하기 / x의 y승 구하기
class Test7 {
public int sum(int n) { //재귀호출로 합 구하기
return n > 1 ? n+sum(n-1) : n;
//10 + 9 + 8 + ... 2 + 1
}
//x의 y승 . 구하기
public double pow(int x, int y) { //재귀 호출로 짜기
double s = 1;
if(y >= 0) {
for(int i=0; i<y; i++) {
s *= x;
}
}else {
for(int i=0; i<-y; i++) {
s /=x;
}
}
return s;
}
}
◾ 재귀호출로 피보나치수열 구하기
1. static 이라서 객체 생성없이 호출할 수 있는 메소드
2. 0 1 1 2 3 5 ... 앞에 2개 값을 더하여서 출력하기 때문에
재귀호출할 때 (n-2) 값과 (n-1) 값을 더해서 출력한다.
public static int fibonacci(int n) { //클래스 메소드
if(n < 2) {
return n;
} else {
return fibonacci(n-2) + fibonacci(n-1);
}
}
for(int i=0; i<10; i++) {
System.out.print(fibonacci(i) + " ");
}
◾ 메소드 오버로딩 : 오버로딩은 메소드 이름, 리턴타입이 같고 인자만 다른 경우!!
public void disp() {
public void disp(short a) {
public void disp(int a) {
public void disp(float a) {
◾ 매개변수의 타입이 동일한 타입이 존재하지 않으면 가장 가까운 타입 출력
public void disp() {
System.out.println("인자 없는 메소드 ");
}
/* overloading 조건을 위배하여 컴파일 오류
public int disp() {
return 1;
}
*/
public void disp(short a) {
System.out.println("short ...");
}
public void disp(int a) {
System.out.println("int ...");
}
public void disp(float a) {
System.out.println("disp...");
}
◾ Short 클래스 : short에 대응하는 클래스
Long 클래스 : long형에 대응하는 클래스
public void disp(Long a) {
System.out.println("Long...");
}
public void disp(Short a) { //대문자 로 시작
System.out.println("Short ...");
}
long b = 10;
dd.disp(b); //long을 처리할 메소드가 없으므로 Wrapper 클래스의 Long이 출력
◾ 비정형 인자라는 것이 있다. 가변 인수라고 한다.
받는 인자의 갯수가 유동적일 때 사용한다.
public int sum(int ... args) { //부정인수 사용 (받으려는 인수 갯수다 다를 때)
int s = 0;
//부정인수는 내부적으로 배열로 처리
for(int n : args) {
s += n;
}
/*
for(int i=0; i<args.length; i++) {
s += args[i];
}
*/
return s;
}
'개발 공부중 > 📑 코드 복습' 카테고리의 다른 글
4. 다양한 클래스 (캘린더, Math, Object, wrapper 클래스 등) (0) | 2023.02.24 |
---|---|
3. 생성자와 this (0) | 2023.02.24 |
1. JAVA 객체와 클래스 (2) | 2023.02.24 |
13. Array 정렬 (버블,삽입,선택 정렬) (0) | 2023.02.24 |
12. Array 2차원 배열 + 퀴즈 (0) | 2023.02.24 |
블로그의 정보
개발자 미니민의 개발로그
mini_min