1. 메서드
- 메서드란, 우리가 일종의 코드를 압축시킨 축약어를 만들어서 그 축약어를 적으면 미리 설정한 코드가 차례대로 실행되는 것이다.
- 예를 들어 어떤 프로그램의 단축키를 누르면 해당 단축키에 설정되어있는 기능이 실행되듯 우리가 그러한 단축키를 만들게 되는 것이다.
- 메서드는 선언과 구현으로 이루어진다.
- 메서드의 선언이란, 해당 메서드가 외부 클래스에서 접근 가능한지, static인지, 메서드가 종료될 때 그 메서드를 실행시킨 곳으로 어떤 데이터 타입의 값을 보내줄지, 이름은 무엇인지, 그 메서드를 실행시킬 때 외부에서 어떤 값을 보내줄지를 지정하는 것이다.
- 또한 해당 메서드를 선언하고 그 안에 그 메서드를 실행시켰을 때 실행할 코드를 우리가 구현하게 된다.
// 메서드의 선언과 구현
접근 제한자 static 리턴타입 메서드이름 (파라미터) {
해당 메서드의 내용
}
2. 접근 제한자 ect.
- 접근 제한자는 해당 메서드에 외부 클래스가 접근 가능한지, 만약 접근 가능하면 외부 패키지에 있는 외부 클래스도 접근 가능한지 등을 설정하는 키워드이다.
- 접근 제한자는 다음과 같이 이루어진다.
- public : 외부 패키지에 저장된 외부 클래스도 해당 메서드를 실행할 수 있다.
- protected: 내부 패키지면 상관없지만 외부 패키지에 저장된 클래스의 경우에는 상속 관계의 클래스일 때만 해당 메서드를 실행할 수 있다.
- default: 내부 패키지의 다른 클래스만 실행 가능하고, 외부 패키지에 있을 경우에는 해당 메서드를 실행시킬 수 없다. default 접근 제한자는 우리가 아무런 접근 제한자를 적어주지 않으면 적용된다.
- private: 해당 메서드가 선언/구현 되어있는 클래스 외에는 해당 메서드를 사용할 수 없다.
- static: 해당 메서드를 클래스 변수의 선언과 초기화 없이 곧장 실행시킬 수 있게 만들어 준다. 단, static 메서드가 같은 클래스의 다른 메서드를 해당 클래스의 변수 선언 없이 사용하려면 그 다른 메서드에도 static이 모두 붙어야 한다.
- 리턴 타입이란, 해당 메서드가 종료될 때 그 메서드를 실행시킨 곳으로 보내줄 값의 데이터 타입을 말한다.
- 만약 아무런 값도 다시 돌려주지 않을 경우 void라고 적는다.
- 리턴 타입이 존재할 시에는 해당 메서드를 구현할 때 반드시 "return"이라는 키워드를 사용해서 해당 데이터의 값을 "돌려주는" 코드를 포함시켜야 한다.
- 만약 리턴 타입이 void일 경우에는 반대로 return을 적으면 에러가 발생한다.
- 메서드 이름은 소문자로 시작하고 낙타등 표기법을 사용하는 동사이다.
- 파라미터는 해당 메서드를 실행할 때 필요로 하는 값을 변수의 형태로 선언만 해둔 것이다.
- 만약 외부로부터 아무런 값도 필요하지 않다면 () 안에 아무것도 안 적어주어도 되지만, 만약 () 안에 파라미터를 설정했을 경우에는 외부에서 해당 메서드를 실행할 때 반드시 그 파라미터와 일치하는 데이터 타입의 값 혹은 변수를 적어주어야 한다.
3. 간단한 예시
public static void main(String[] args) {
// 이름을 예쁘게 출력하는 코드를 만들고 3번 반복해보자
printName();
printName();
printName();
// int 변수 2개의 산술연산결과값을 예쁘게 출력하는 코드
// 1. 5와 7에 대한 결과
int num1 = 5;
int num2 = 7;
printCalcResult(num1, num2);
// 2. 7과 5에 대한 결과
printCalcResult(num2, num1);
// 3. 변수가 아닌 int 값 10과 12에 대한 결과
printCalcResult(10, 12);
// int 값 3개에 대한 평균을 구하는 코드
double average = calcAverage(3, 4, 5);
average = calcAverage(4, 5, 10);
average = calcAverage(4, 9, 10);
average = calcAverage(4, 6, 10);
average = calcAverage(4, 5, 12);
}
// 이름을 예쁘게 출력하는 printName() 메서드
// 이 메서드의 리턴 타입은? void
// 이 메서드의 파라미터는? 없다.
public static void printName() {
System.out.println("\n===================================");
System.out.println("-----------------------------------");
System.out.println("\t김\t땡\t땡");
System.out.println("-----------------------------------");
System.out.println("===================================\n");
}
// 2개의 int 값에 대한 산술연산자 결과값을 예쁘게 출력하는 printCalcResult() 메서드
// 이 메서드의 리턴 타입은? void
// 이 메서드의 파라미터는? int a, int b
public static void printCalcResult(int a, int b) {
System.out.println("\n===================================");
System.out.println("\t결\t\t과");
System.out.println("===================================\n");
System.out.printf("%d + %d = %d\n", a, b, a + b);
System.out.printf("%d - %d = %d\n", a, b, a - b);
System.out.printf("%d * %d = %d\n", a, b, a * b);
System.out.printf("%d / %d = %d\n", a, b, a / b);
System.out.printf("%d %% %d = %d\n", a, b, a % b);
System.out.println("===================================\n");
}
// 3개의 int 값에 대한 평균을 구해주는 calcAverage() 메서드
// 이 메서드의 리턴 타입은? double
// 이 메서드의 파라미터는? int, int, int
public static double calcAverage(int a, int b, int c) {
double average = (a + b + c) / 3.0;
// return 명령어의 경우, 한가지 주의할 점이 있는데,
// return 키워드가 실행되면 곧장 해당 메서드는 거기서 종료가 된다.
// if 같은 조건문 안에 return을 더 써줄 수도 있지만
// 메서드의 가장 바깥 쪽에 있는 return 키워드 이후에는
// 아무런 코드를 실행시킬 수 없다.
return average;
}
4. 실전
- 사용자로부터 번호, 이름, 국어, 영어, 수학 순으로 입력을 받아서 다음과 같이 출력되는 프로그램을 작성하려고 한다.
- 번호: 0##번 이름: ###
- 국어: 0##점 영어: 0##점 수학: 0##점
- 총점: 0##점 평균: 0##.##점
- 단, 입력과 출력을 분리해서 사용자가 입력을 누를 때에만 입력이 되고 출력을 누르면 출력이 되게 코드를 작성한다.
- 사용자가 종료를 선택하기 전까지는 해당 기능이 무한하게 반복되게 한다.
- 만약 사용자가 입력한 적 없이 출력을 선택하면 "아직 입력된 정보가 없습니다."라고 출력되게 한다.
import java.util.Scanner;
public class GradeBook {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int id = 0;
String name = "";
int korean = 0;
int english = 0;
int math = 0;
boolean inputSwitch = false;
while (true) {
System.out.println("숫자를 입력하세요.");
System.out.println("1. 입력 2. 출력 3. 종료");
System.out.print("> ");
int userChoice = scanner.nextInt();
if (userChoice == 1) {
// 입력 코드 구현
System.out.println("번호를 입력하세요.");
System.out.print("> ");
id = scanner.nextInt();
System.out.println("이름을 입력하세요.");
System.out.print("> ");
scanner.nextLine();
name = scanner.nextLine();
System.out.println("국어 점수를 입력하세요.");
System.out.print("> ");
korean = scanner.nextInt();
while (korean < 0 || korean > 100) {
System.out.println("잘못 입력하셨습니다.");
System.out.println("국어 점수를 입력하세요.");
System.out.print("> ");
korean = scanner.nextInt();
}
System.out.println("영어 점수를 입력하세요.");
System.out.print("> ");
english = scanner.nextInt();
while (english < 0 || english > 100) {
System.out.println("잘못 입력하셨습니다.");
System.out.println("영어 점수를 입력하세요");
System.out.print("> ");
english = scanner.nextInt();
}
System.out.println("수학 점수를 입력하세요.");
System.out.print("> ");
math = scanner.nextInt();
while (math < 0 || math > 100) {
System.out.println("잘못 입력하셨습니다.");
System.out.println("수학 점수를 입력하세요.");
System.out.print("> ");
math = scanner.nextInt();
}
inputSwitch = true;
} else if (userChoice == 2) {
// 출력 코드 구현
if (inputSwitch) {
System.out.printf("번호: %03d번 이름: %s\n", id, name);
System.out.printf("국어: %03d점 영어: %03d점 수학: %03d점\n", korean, english, math);
int sum = korean + english + math;
double average = (double) sum / 3;
System.out.printf("총점: %03d점 평균: %06.2f점\n", sum, average);
} else {
System.out.println("아직 입력된 정보가 없습니다.");
}
} else if (userChoice == 3) {
// 종료
System.out.println("사용해주셔서 감사합니다.");
break;
}
}
}
- 이제 여기서 사용자가 점수를 입력하면 올바른 점수를 리턴해주는 메서드를 만들어 보도록 한다.
- 국어, 영어, 수학 점수를 입력 받을 때 해당 메서드를 사용하고, 출력도 별개의 메서드로 분리해서 프로그램을 작성해 보자.
import java.util.Scanner;
public class GradeBookD {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int id = 0;
String name = "";
int korean = 0;
int english = 0;
int math = 0;
boolean inputSwitch = false;
while (true) {
System.out.println("숫자를 입력하세요");
System.out.println("1. 입력 2. 출력 3. 종료");
System.out.print("> ");
int userChoice = scanner.nextInt();
if (userChoice == 1) {
// 입력 코드 구현
System.out.println("번호를 입력하세요.");
System.out.print("> ");
id = scanner.nextInt();
System.out.println("이름을 입력하세요.");
System.out.print("> ");
scanner.nextLine();
name = scanner.nextLine();
korean = setScore(scanner, "국어");
english = setScore(scanner, "영어");
math = setScore(scanner, "수학");
inputSwitch = true;
} else if (userChoice == 2) {
// 출력 코드 구현
if (inputSwitch) {
printInfo(id, name, korean, english, math);
} else {
System.out.println("아직 입력된 정보가 존재하지 않습니다.");
}
} else if (userChoice == 3) {
// 종료
System.out.println("사용해주셔서 감사합니다.");
break;
}
}
}
public static int setScore(Scanner scanner, String subject) {
int score = 0;
final int SCORE_MIN = 0;
final int SCORE_MAX = 100;
System.out.println(subject + " 점수를 입력하세요.");
System.out.print("> ");
score = scanner.nextInt();
while (!(score >= SCORE_MIN && score <= SCORE_MAX)) {
System.out.println("잘못 입력하셨습니다.");
System.out.println(subject + " 점수를 입력하세요.");
System.out.print("> ");
score = scanner.nextInt();
}
return score;
}
public static void printInfo(int id, String name, int korean, int english, int math) {
final int SUBJECT_NUM = 3;
System.out.printf("번호: %d번 이름: %s\n", id, name);
System.out.printf("국어: %d점 영어: %d점 수학: %d점\n", korean, english, math);
int sum = korean + english + math;
double average = (double) sum / SUBJECT_NUM;
System.out.printf("총점: %d점 평균: %06.2f점\n", sum, average);
}
}
'~2023.02 > 외부교육' 카테고리의 다른 글
[JAVA] 콜렉션(Collection) (0) | 2022.03.19 |
---|---|
[JAVA] 객체(Object) & 캡슐화(Encapsulation) (0) | 2022.03.19 |
[JAVA] 배열의 동적 할당(Dynamic Allocation) (0) | 2022.03.16 |
[JAVA] Call By Valeue(값에 의한 호출) & Call By Reference(참조에 의한 호출) (0) | 2022.03.15 |
1주차(22.03.02~03.04) (0) | 2022.03.05 |