Binary World

JAVA CLASS : Method 본문

개발자의 길/JAVA

JAVA CLASS : Method

모쿠 2016. 12. 29. 11:31

<Java Practice>


*MethodMain02(사칙연산 메소드 생성)


public class MethodMain02 {


// 메소드 이름: add

// 기능: 두 개의 정수를 매개변수로 전달 받아서, 두 정수의 합을 리턴

// 리턴 타입: int

// 매개변수: int x, int y

public static int add(int x, int y) {

return x + y;

} // end add


// 메소드 이름: sub

// 기능: 정수 두 개를 전달 받아서, 그 차를 리턴

// 리턴 타입: int

// 매개변수: int x, int y

public static int sub(int x, int y) {

return x - y;

} // end sub


// 메소드 이름: mul

// 기능: 두 개의 실수를 전달 받아서 두 수의 곱을 리턴하는 함수

// 리턴 타입: double

// 매개변수: doube x, double y

public static double mul(double x, double y) {

return x * y;

}


// 메소드 이름: div

// 기능: 두 개의 실수를 전달 받아서 두 수의 곱을 리턴하는 함수

// 리턴 타입: double

// 매개변수: doube x, double y

public static double div(double x, double y) {

return x / y;

}


public static void main(String[] args) {

System.out.println("메소드");

int result = add(5, 6);

System.out.println(result);


System.out.println();

result = sub(100, 5);

System.out.println(result);


System.out.println();

double mulresult;

mulresult = mul(3, 6);

System.out.println(mulresult);

double divresult;

divresult = div(6, 5);

System.out.println(divresult);

// ctrl + 클릭 : 메소드 정의한 곳으로 점프


} // end main()


// 메소드: 기능을 수행하기 위한 코드

// 메소드는 클래스 안에서, 다른 메소드 바깥에서 만듬(정의)

// (주의) 메소드 안에서 또다른 메소드를 만들 수 는 없다!

// 메소드 정의:

// [수식어] 리턴타입 메소드이름([매개변수], ...) { 실행문; }

// 수식어 : public, private, static, ... - 생략 가능

// 리턴타입 : 자료타입(int, double, String, ...), void

// 매개변수: 매세도를 호출할 때 전달하는 데이터

// 전달받는 데이터가 없으면 매개변수 선언이 없어도 됨.

// ()는 생략할 수 없다!

// {...}: 메소드 본체(body)


} // end class methodmain02

 


*MethodMain03(성적 처리 프로그램)


import java.util.Scanner;


public class MethodMain03 {

//세 과목의 합

public static int calcTotal(int kor, int eng, int math){

return kor + eng + math;

} // end calcTotal()

//세 과목의 평균

public static double calcAverage(int total){

return total / 3.0;

} // end calcAverage

public static char calcGrade(double avg){

if (avg >= 90){

return 'A';

}

else if (avg >= 80){

return 'B';

}

else if (avg >= 70){

return 'C';

}

else {

return 'F';

}

}


public static void main(String[] args) {

// 성적 처리 프로그램

// 1. 국영수 점수를 입력 받아서 저장

// 2. 입력받은 점수를 출력

// 3. int calcTotal(int kor, int eng, int math) 세 과목의 총점을 계산

// 메소드를 정의하고 호출

// 4. double calcAverage(int total) 메소드를 정의하고,

// 호출해서 세 과목의 평균을 출력

// 5. char calcGrade(double avg) 메소드를 정의하고,

// 호출해서 성적('A', 'B', 'C', 'F')을 출력

System.out.println("===성적 처리 프로그램===");


Scanner sc = new Scanner(System.in);

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

int korScore = sc.nextInt();

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

int engScore = sc.nextInt();

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

int mathScore = sc.nextInt();

sc.close();

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

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

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

System.out.println("수학 : " + mathScore);

int total = calcTotal(korScore, engScore, mathScore);

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

double avg = calcAverage(total);

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

char grade = calcGrade(avg);

System.out.println("성적 : " + grade);


} // end main()


} // end class MethodMain03



*MethodMain04(배열을 매개변수로 갖는 메소드)

import java.util.Scanner;


public class MethodMain04 {


public static void main(String[] args) {

// 배열을 매개변수로 갖는 메소드

// 점수(int) 3개를 저장할 수 있는 배열 선언

int[] scores = new int[3];

// 배열 점수 3개를 저장하는 메소드를 호출

inputScores(scores);

// 배열에 있는 점수를 출력하는 메소드를 호출

printScores(scores);

// 배열에 저장된 점수들의 총합을 리턴하는 메소드

int total = calcTotal(scores);

System.out.println(total);

// 배열에 저장된 점수들의 최대값과 최소값을 찾는 메소드

int max = findMax(scores);

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

int min = findMin(scores);

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

} // end main()

// 점수를 입력 받아서 배열에 저장하는 메소드 정의

public static void inputScores(int[] scores){

Scanner sc = new Scanner(System.in);

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

System.out.println("점수" + i + ">");

scores[i] = sc.nextInt();

} // end for

sc.close();

} // end inputScores()

// 배열안에 점수를 출력하는 메소드 정의

public static void printScores(int[] scores){

for(int x : scores){

System.out.println(x);

}

} // end printScores

// 배열에 저장된 점수들의 총합을 리턴하는 메소드

public static int calcTotal(int[] scores){

int sum = 0;

for(int x : scores)

{

sum += x; 

}

return sum;

} // end calcTotal()

// 배열에 저장된 최대값 찾기

public static int findMax(int[] scores){

int max = scores[0]; //배열의 0번째 원소를 최대값이라고 가정

for(int i=1; i < scores.length; i++){

if(max <= scores[i]){

max = scores[i];

}

}

return max;

}


// 배열에 저장된 최소값 찾기

public static int findMin(int[] scores){

int min = scores[0]; //배열의 0번째 원소를 최대값이라고 가정

for(int i=1; i < scores.length; i++){

if(min >= scores[i]){

min = scores[i];

}

}

return min;

}

} // end class MethodMain04 



* MethodMain05(배열 리턴 메소드)


import java.util.Scanner;


public class MethodMain05 {


public static void main(String[] args) {

// 배열을 리턴하는 메소드

int[] scores = inputNumbers();

System.out.println("결과 확인:");

for (int x : scores){

System.out.println(x);

}


} // end main()

// 메소드 이름 : inputNumbers

// 리턴 타입 : int[]

// 매개변수: 없음

// 기능: 숫자 5개를 입력 받아서 배열에 저장하고, 그 배열을 리턴

public static int[] inputNumbers(){

int[] num = new int[5];

Scanner sc = new Scanner(System.in);

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

System.out.println(i + "-th 숫자 >");

num[i]= sc.nextInt();

}

sc.close();

return num;

} // end inputNumbers()


} // end class MethodMain05 



*MethodMain06(메소드 오버로딩)


 public class MethodMain06 {


public static void main(String[] args) {

// 메소드 overloading:

// 1. 매개변수의 개수가 다르거나

// 2. 매개변수의 타입이 다른 경우

// 같은 이름으로 메소드를 정의할 수 있다.

// (주의) 메소드의 ㅣㄹ턴 타입만 다른 경우는 같은 이름으로 메소드를 정의할 수 없다

sayHello();

sayHello("진혁");

sayHello("진혁", 20);

sayHello(20, "진혁");

             // 자주 쓰이는 오버로딩

System.out.println();

System.out.println("문자열");

System.out.println(1);

System.out.println(1.0);

System.out.println(true);


} // end main()

// public static void sayHello() {

// System.out.println("hello");

// return 0;

// }

//

// // 리턴 타입만 같은 경우는 overloading 할 수 없음.


public static void sayHello(){

System.out.println("안녕하세요~");

}

public static void sayHello(String name){

System.out.println("Hello~");

System.out.println("제 이름은 " + name + "입니다.");

}

public static void sayHello(String name, int age){

System.out.println("이름: " + name);

System.out.println("나이: " + age);

}

public static void sayHello(int age, String name){

System.out.println("제 이름은 " + name);

System.out.println("제 나이는 " + age);

}


} // end class MethodMain06


'개발자의 길 > JAVA' 카테고리의 다른 글

JAVA CLASS : 클래스  (0) 2016.12.29
JAVA CLASS : 연습(배열, 피보나치 수열)  (0) 2016.12.29
JAVA CLASS : 연습(반복문)  (0) 2016.12.29
JAVA CLASS : 배열  (0) 2016.12.29
JAVA CLASS : 반복문(for, while, loop)  (0) 2016.12.29
Comments