package chapter07;
public class MethodTest1 {
public static void main(String[] args) {
// Method
//메서드 호출
System.out.println("1 ~ 10 = " + calcSum(1,10));
System.out.println("15 ~ 100 = " + calcSum(15,10));
} //main
//메서드 정의
public static int calcSum(int from, int to) { //여기선 1을 from이라는 변수에 저장, 10은 변수 to에 저장 //즉 int from =1; , int to 10;과 같은 의미
int sum = 0;
for (int i = 0; i < from; i++) {
sum += i;
}
return sum; //되돌아 가는데 sum이라는 데이터 들고 간다. 근데 무슨 종류의 데이터를 들고갈건지는
//public static int calcSum(int from, int to) 의 int로 정의 했기에 int타입 sum을 리턴하겠다.
//참고로 데이터 타입은 꼭 써야함
//=> public static void main(String[] args) { 에서도 아무것도 돌려주지 않지만 아무것도 덜려주지 않는다는 의미의
//void 를 적어준거임
}
}//class
<실행결과>
1 ~ 10 = 0 15 ~ 100 = 105
package chapter07;
public class MethodTest2 {
public static void main(String[] args) {
//method 호출부
method1();
String s = method2(); //String s = "hello java"즉 String s = method2();과 동일
System.out.println(s);
int[] arr = {0,1,2,3};
method3(arr);
System.out.println();
System.out.println(method4(1,5));
}//main
//method 정의부
//1.파라미터x,반환값x
public static void method1() {
System.out.println("파라미터가 없고 반환값이 없는 메서드 실행");
return;//생략가능
}
//2..파라미터x,반환값o
public static String method2() {
System.out.println("파라미터가 없구 문자열을 반환하는 메서드 실행");
return "hello java";
}
//3.파라미터o,반환값x
public static void method3(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
}
//4.파라미터o,반환값ㅇ
public static int method4(int a, int b) {
int sum = a + b;
return sum;
}
}//class(MethodTest2)
<실행결과>
파라미터가 없고 반환값이 없는 메서드 실행 파라미터가 없구 문자열을 반환하는 메서드 실행 hello java 0 1 2 3 6
package chapter07;
public class MethodTest3 {
public static void main(String[] args) {
int year = 2024;
int month = 2;
int days = getMonthDays(year, month);
System.out.println(year + "년 " + month + "월은 " + days + "일까지 있습니다.");
}
public static int getMonthDays(int year, int month) {
int[] arDays = {
0,31,28,31,30,31,30,31,31,30,31,30,31
};
if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 ==0 ){
return 29;
}
return 28;
} else {
return arDays[month];
}
}
}
<실행결과>
2024년 2월은 29일까지 있습니다.
<풀이>
4년에 한번 돌아오는 2월 29일
package chapter07;
public class MethodTest04 {
public static void main(String[] args) {
int num = 2;
getDouble(num);
System.out.println("num = " + num);
int[] arr = {2,8,6};
getDouble(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(
"arr[" + i + "]" + arr[i]);
}
}
//복제하여 바꾼값 리턴
static int getDouble(int value) {
value *= 2;
return value;
}
// 파라미터o,반환값x
//주소값을 참조하여 죽소값 숫자 바꾸기
static void getDouble (int[] value) {
value[0] *= 2;
}
}
<실행결과>