1. 메소드의 매개변수(parameter)
접근제한자 반환타입 메소드명(매개변수타입 매개변수값) { }
- 값을 전달받기 위한 변수
- 매개변수는 0개 이상 정의 가능
- 매개변수의 타입은 기본자료형, 참조자료형 모두 가능
- 메소드를 호출하는 측에서는 반드시 매개변수에 맞게 인자(Argument)값을 전달
1-1. 매개변수가 없는 메소드
- 먼저, Sample 클래스에 메소드 생성
public class Sample {
// 매개변수가 없는 메소드
public void test1() {
System.out.println("매개변수 없음");
}
- SampleApp 클래스에서 메소드 실행(호출)
public class SampleApp {
public static void main(String[] args) { // 메인메소드가 있어야 프로그램 실행의 시작임
Sample sample = new Sample();
// 매개변수가 없는 메소드 실행(=호출)
sample.test1(); // ( ) 메소드 실행시 전달할 값 (인자: Argument)
매개변수 없음
1-2. 매개변수가 있는 메소드
* 클래스의 구성요소인 메소드를 실행하기 위해서는 반드시 객체가 있어야 함
( = Sample 클래스에 메소드를 넣고, SampleApp 클래스를 객체로 사용해서 메소드를 실행해야 함)
* 메소드를 실행할 때 sample.test 라고 치면 뜨는 화면
test() : void - Sample 설명
test : 메소드이름
() : 매개변수
void : 반환타입
Sample : 해당 메소드가 들어있는 클래스명
1-2. 1) 메소드의 매개변수 인자가 '기본자료형값'
- Sample 클래스에 test2 메소드 생성
public class Sample {
// 기본자료형 타입의 매개변수가 있는 메소드
// 매개변수 : int x, int y
// 정수 2개 요구
public void test2(int x, int y) {
System.out.println("x의 값: "+ x);
System.out.println("y의 값: "+ y);
x++;
y++;
System.out.println("x의 값: "+ x);
System.out.println("y의 값: "+ y);
}
- SampleApp 클래스에서 test2 메소드 실행(호출)
public class SampleApp {
public static void main(String[] args) {
// 기본형타입 매개변수가 있는 메소드 실행(=호출)
Sample sample = new Sample();
int x = 10; // main 메소드
int y = 20; // main 메소드
sample.test2(x, y); // test2 메소드 실행 후 종료
System.out.println("SampleApp x의 값: "+x); // 다시 main 메소드만 남음
System.out.println("SampleApp y의 값: "+y); // 다시 main 메소드
x의 값: 10
y의 값: 20
x의 값: 11
y의 값: 21
SampleApp x의 값: 10
SampleApp y의 값: 20
- 이미지로 표현
- 메소드영역 = 스택영역 ( 선입후출 = 맨 상단에 있는 저장공간의 변수에만 액세스 가능)
- 1. SampleApp의 main 메소드 실행
- 스택영역에 main 메소드 전용의 변수 저장공간 추가.
- main 메소드의 매개변수, 지역변수가 해당 저장공간에 추가.
- 스택에 main 메소드만 담겨있으므로 main 메소드의 변수 저장공간에 엑세스 가능 - 2. test2 메소드 실행
- 스택영역에 test2 메소드 전용의 변수 저장공간 추가.
- test2 메소드의 매개변수, 지역변수가 해당 저장공간에 추가.
- 스택에 test2 메소드가 맨 상단에 위치해있으므로 test2 메소드의 변수 저장공간에 엑세스 가능
- test2 메소드가 종료되면 스택에서 test2 저장공간이 사라지고 다시 main 메소드가 남음
- 1. SampleApp의 main 메소드 실행
- 메소드 실행 과정
- public class SampleApp { // SampleApp 객체 안에서 메소드 실행
public static void main(String[] args) { // main 메소드 실행
Sample sample = new Sample(); // Sample 객체를 생성해서 그 주소값을 sample 변수에 저장
int x = 10; // main 메소드 안에 변수를 만들고 값 대입
int y = 20;
sample.test2(x, y); // sample변수가 참조하는 객체의 test2메소드 실행(호출)하고,
그 안에 int값 x, y를 대입 ( -> 이 값이 test2 메소드의 매개변수에 전달(복사))
- <test2메소드>
- public class Sample { // Sample 클래스
public void test2(int x, int y) { // test2 메소드 선언부
System.out.println("x의 값: "+ x); // main 메소드에서 저장된 x, y의 값이 매개변수를 통해 전달(복사)
System.out.println("y의 값: "+ y); // x=10, y=10
x++;
y++;
System.out.println("x의 값: "+ x); // x=11, y=21
System.out.println("y의 값: "+ y);
} // 출력 후 test2 메소드는 종료 (= 스택에서 test2 메소드가 사라짐 )
- <test2메소드>
- System.out.println("SampleApp x의 값: "+x); // 다시 main 메소드만 남음
System.out.println("SampleApp y의 값: "+y); // x=10, y=10 왜?
메소드 안에 있는 변수는 메소드가 종료되면 모두 사라짐
Sample 클래스 안에 있는 test2 메소드의 x, y ≠ SampleApp 객체 안에 있는 main 메소드의 x, y
( main 메소드의 값이 매개변수를 통해 test2 메소드로 복사된거지 같은 변수가 X )
- public class SampleApp { // SampleApp 객체 안에서 메소드 실행
1-2. 2) 메소드의 매개변수 인자로 '클래스타입(객체의 주소값)'
- 메소드의 매개변수가 참조자료형 타입이면 값이 아닌, 그 객체의 '주소값'을 요구하는 것
- 해당 메소드를 호출하기 위해서는 호출한 객체에서 매개변수에서 지정한 타입에 해당하는 객체의 주소값을 이미 가지고 있어야 함
(메소드가 들어있는 객체를 생성하는 것과 별개로, 매개변수의 타입에 해당하는 객체를 먼저 생성
-> 클래스 안의 메소드의 매개변수 설정 -> 메소드 호출) - 객체의 주소값을 매개변수의 인자로 전달하면, 주소값을 전달받은 그 메소드도 같은 객체를 참조하게 된다.
- 매개변수에 null값도 들어갈 수 있지만, 객체의 주소값을 전달받을 때 null값을 전달받을 가능성도 있다면 꼭 null이 아닌지 체크하는 코드가 있어야 한다. (ex. if(book != null) )
- Sample 클래스
public class Sample {
// 클래스타입의 매개변수가 있는 메소드 (기본형이 아닌 다른타입이 있으면 무조건 객체를 달라는 뜻)
// 매개변수 : SampleValue sampleValue
// SampleValue클래스로 생성한 객체의 주소값을 요구
public void test3(SampleValue sampleValue) {
System.out.println("test3의 sampleValue: "+ sampleValue);
System.out.println("test3의 sampleValue.x: "+ sampleValue.x);
System.out.println("test3의 sampleValue.y: "+ sampleValue.y);
System.out.println("test3의 sampleValue가 참조하는 객체의 x,y값 변경하기");
sampleValue.x=300;
sampleValue.y=500;
}
- SampleValue 객체 생성 (매개변수의 타입에 해당하는 객체)
public class SampleValue {
int x;
int y;
}
- SampleApp 객체
public class SampleApp {
public static void main(String[] args) {
// 클래스타입 매개변수가 있는 메소드 실행(=호출)
Sample sample = new Sample(); // Sample 객체 생성
SampleValue sampleValue = new SampleValue(); // 매개변수타입인 SampleValue객체 생성
System.out.println("main의 SampleValue: "+sampleValue); // sampleValue가 참조하는 객체의 고유정보
sampleValue.x = 100; // sampleValue변수가 바라보는 객체의 x변수에 100 대입
sampleValue.y = 200;
sample.test3(sampleValue); // sampleValue 참조변수에 저장된 SampleValue 객체의 주소값을 전달한다.
// sample변수가 가리키는 객체 안에 있는 test3 메소드의 인자에 sampleValue변수가 갖는 SampleValue객체의 주소값을 준다.
System.out.println("main의 sampleValue.x의 값: " + sampleValue.x);
System.out.println("main의 sampleValue.y의 값: " + sampleValue.y);
}
main의 SampleValue: day9.SampleValue@5e91993f
test3의 sampleValue: day9.SampleValue@5e91993f
test3의 sampleValue.x: 100
test3의 sampleValue.y: 200
test3의 sampleValue가 참조하는 객체의 x,y값 변경하기
main의 sampleValue.x의 값: 300
main의 sampleValue.y의 값: 500
- 이미지로 표현
- public class SampleApp { // SampleApp 객체 안에서 메소드 실행
public static void main(String[] args) { // main 메소드 생성
Sample sample = new Sample(); // Sample 객체를 생성하고 그 주소값을 sample 변수에 저장
SampleValue sampleValue = new SampleValue();
// Sample 클래스에 있는 test3 메소드를 호출하려면, 그 메소드의 매개변수타입인 SampleValue 객체의 주소값을 갖고 있어야 함 = SampleValue 객체 생성 후 변수에 주소값 대입
= sampleValue변수가 SampleValue 객체를 참조 !
(참조형 매개변수는 주소값을 매개인자로 요구하니까)
-> 스택의 main메소드 저장공간 안에 sample, sampleValue 변수 생성 후, 그 변수가 가리키는 객체의 주소값 저장 - sampleValue.x = 100;
sampleValue.y = 200;
// sampleValue 변수가 가리키는 SampleValue 객체 안에 x, y 변수가 있고, 그 안에 100, 200 값 저장 - sample.test3(sampleValue);
// sample변수가 가리키는 객체 안에 있는 test3메소드의 매개인자에 sampleValue변수가 가리키는 SampleValue객체의 주소값을 대입, 복사 (0x2222)
-> test3변수도 SampleValue객체를 참조하게 됨! -> test3메소드 실행- < test3메소드 >
public class Sample {
public void test3(SampleValue sampleValue) { // 스택의 test3블록에 매개인자로 받은 sampleValue변수 생성
( 근데 주소값을 받았으니까 얘도 같은 주소값을 갖게 됨
-> sampleValue변수와 같은 SampleValue 객체를 참조함 )
System.out.println(sampleValue.x); // 같은 객체를 바라보고 있으므로,
System.out.println(sampleValue.y); main메소드에서 sampleValue를 통해 저장했던 x,y값 출력
sampleValue.x = 300; // sampleValue변수가 참조하는 객체의 x,y에 300,500 대입
sampleValue.y = 500; ( = sampleValue변수가 참조하는 객체)
} // test3 메소드 종료
(* 매개인자가 기본형을 받을 때 (call by value)
: 값을 복사해서 줬기 때문에 메소드 안에서 값을 바꿔도 메소드 종료후 main메소드에서는 값이 안바뀜
* 매개인자가 주소값을 전달(복사)받을 때 (call by reference)
: main메소드의 변수와 test3메소드의 변수가 참조하는 객체가 같기 때문에 원본(main메소드)의 값도 바뀜 - System.out.println(sampleValue.x); // test3 메소드 종료 후 남은 main메소드인데 원본값이 바꼈음
System.out.println(sampleValue.y); // x=300, y=500
- < test3메소드 >
※ 주소값을 매개변수로 가져서 복사(전달) => 내가 참조하는 객체를 너도 참조해라
2. 메소드의 반환타입과 반환값
2-1. 반환타입이 없는 경우
- Sample 클래스에 메소드 생성
public class Sample {
// 반환타입이 void인 메소드
// 메소드를 호출한 측에게 제공하는 값이 존재하지 않는다.
public void hello() {
System.out.println("안녕하세요");
}
// 반환타입이 void + 매개변수가 있는 메소드
// (매개변수 주소값을 받지만, String객체는 내장되어 있기 때문에 안만들어도 됨?)
public void greeting(String name) {
System.out.println(name + "님 생일을 축하드립니다.");
}
}
- SampleApp 객체에서 메소드 실행(호출)
public class SampleApp2 {
public static void main(String[] args) {
Sample sample = new Sample();
// 반환타입이 void인 메소드의 호출
sample.hello();
// 반환타입이 void + 매개변수가 있는 메소드의 호출
sample.greeting("김유신");
}
}
안녕하세요
김유신님 생일을 축하드립니다.
2-2. 반환타입이 있는 경우
2-2. 1) 반환타입이 기본자료형인 경우 (정수, 실수, 문자, 불린)
- 반환 : 메소드의 실행결과로 (어떤 동작, 기능의 결과), 어떤 '값'이 나오는 것 !
- Sample 클래스에 메소드 생성
public class Sample {
// 정수 2개를 전달 받아서 합계를 출력으로 제공하는 메소드
// 반환타입이 정수인 경우
// 구현부에서는 return문을 사용해서 정수'값'을 반환하는 코드가 포함되어 있어야 한다.
public int plus(int x, int y) {
int result = x + y;
return result;
}
// 총점과 과목갯수를 전달받아서 평균값을 출력으로 제공하는 메소드
// 반환타입이 실수인 경우
// 반환타입과 매개변수 타입은 일치할 필요가 없다.
double getAverage(int total, int count) {
double average = (double) total/count;
return average;
}
// 정수를 전달받아서 짝수인지 여부를 제공하는 메소드
// 반환타입이 boolean인 경우
boolean isEven(int number) {
if (number%2 == 0) {
return true; // 짝수인 경우 true반환
} else {
return false; // 홀수인 경우 false반환
}
}
// 배열과 정수를 전달받아서, 배열에 그 숫자가 포함되어 있는지 여부를 제공하는 메소드
// 반환타입이 boolean인 경우
boolean isExist(int[] numbers, int value) {
boolean result = false;
for (int num : numbers) {
if (num == value) { // 배열의 모든 숫자를 하나씩 꺼내서 value값과 일치하는지 비교한다.
result = true; // value값과 일치하는 값이 있을 때만 result값은 true가 된다.
break;
}
} // for문을 사용해서 value와 일치하는 값이 배열에 하나도 없는 경우에는 result값은 false값이 계속 유지된다
return result; // 배열에 value와 일치하는 값이 존재할 때만 true가 반환된다.
}
}
- SampleApp2 객체에서 메소드 실행
public class SampleApp2 {
public static void main(String[] args) {
Sample sample = new Sample();
// 반환타입이 int로 지정된 메소드의 호출
int result1 = sample.plus(10, 30); // sample변수가 참조하는 객체의 plus메소드를 실행한 결과값을 result1 변수에 대입
System.out.println("반환값: " + result1); // 40이 출력된다.
// 위의 내용을 plus메소드의 결과값을 변수에 저장하지 않고 바로 출력
System.out.println(sample.plus(100, 200));
int value2 = sample.plus(50, 100);
System.out.println("반환값: " + value2); // 150이 출력된다.
// 반환타입이 double로 지정된 메소드의 호출
double value3 = sample.getAverage(180, 3);
System.out.println("반환값: " + value3); // 60이 출력된다.
// 반환타입이 boolean으로 지정된 메소드의 호출
boolean value4 = sample.isEven(7);
System.out.println("반환값: " + value4); // false가 출력된다.
boolean value5 = sample.isEven(8);
System.out.println("반환값: " + value5); // true가 출력된다.
// 반환값이 boolean으로 지정된 메소드의 호출
int[] arr = {1, 2, 3, 4, 5, 6};
boolean value6 = sample.isExist(arr, 9);
System.out.println("반환값: " + value6); // false가 출력된다.
boolean value7 = sample.isExist(arr, 3);
System.out.println("반환값: " + value7); // true가 출력된다.
}
}
※ 반환타입이 있는 경우 return ~; 은 필수
- public void minuse(int x, int y) { // 반환타입이 없을 때는 return 없음
return; // return=0; 이라고 안하고 이렇게는 괜찮
}- public int plus(int x, int y) { // 이대로만 하면 return값이 없어서 오류
if (x > y) {
return x; // 반환타입이 있는 경우는 모든 경우에서 이게 반드시 있어야 함!
} else {
return y;
}
}
- return 값 (값손실이 없는 방향으로 형변환 후 반환)
// 기본자료형타입의 반환타입이 있는 메소드
public double plus(int x, int y) {
int z = x + y;
return z;
}
// 정수타입의 z값이 실수타입의 값으로 형변환된 후 반환
public double plus2(int x, int y) {
int z = x + y;
return z; // 정수가 double로 바뀌는건 값손실이 없어서 ok
}
// 실수타입의 z값이 정수타입의 값으로 형변환되면 데이터 손실 발생으로 컴파일 오류(문법오류)
public int plus3(double x, double y) {
double z = x + y;
return z; // double이 int로 반환되면 값손실 때문에 x
}
// 4byte 정수타입의 z값이 8byte 정수타입의 값으로 형변환된 후 반환
public long plus4(int x, int y) {
int z = x + y;
return z;
}
- 반환타입이 있고, 매개변수가 객체의 주소값인 경우
빈 문자열이면 true, 값이 있으면 false인 메소드
public class Sample {
public boolean isEmptyString(String str) {
if(str == null) { // (값을 전달받지 못한) null도 true로 판단하겠다
return true;
}
int len = str.length();
if (len > 0) {
return false;
} else {
return true;
}
}
public class SampleApp2 {
public static void main(String[] args) {
Sample sample = new Sample();
// 반환타입이 boolean이고 매개변수가 String인 메소드 호출
// sample변수가 참조하고 있는 isEmptyString메소드에 ()값을 전달했을때의 결과값을 result2변수에 대입
boolean result2 = sample.isEmptyString("");
boolean result3 = sample.isEmptyString("안녕하세요.");
boolean result4 = sample.isEmptyString(null); //객체의 주소값 X, str에 들어가는 값=null
//null값 지정을 안하면 nullpointerexception 에러
System.out.println("결과값2: "+ result2);
System.out.println("결과값3: "+ result3);
System.out.println("결과값4: "+ result4);
결과값2: true
결과값3: false
결과값4: true
2-2. 2) 반환타입이 참조자료형인 경우 (배열, 객체)
- 객체나 배열의 '주소값'이 반환 (SampleValue 객체를 참조하고 있는 객체의 주소값이 반환)
- 이 메소드는 반환타입에 지정된 객체의 주소값을 제공할 책임이 있다
public class Sample {
public SampleValue createSampleValue(int num1, int num2) {
// 반환타입인 SampleValue 객체를 생성하고, 생성된 객체의 주소값을 참조변수에 대입
SampleValue sampleValue = new SampleValue();
sampleValue.x = num1;
sampleValue.y = num2;
// 참조변수에 저장된 주소값 반환
return sampleValue;
}
}
public class SampleApp2 {
public static void main(String[] args) {
Sample sample = new Sample();
// 반환타입이 참조자료형인 메소드 호출
SampleValue result5 = sample.createSampleValue(10, 20);
SampleValue result6 = sample.createSampleValue(100, 200);
SampleValue result7 = sample.createSampleValue(500, 620);
System.out.println("result5가 참조하는 객체: "+ result5);
System.out.println(result5.x + ", " + result5.y);
System.out.println("result6가 참조하는 객체: "+ result6);
System.out.println(result6.x + ", " + result6.y);
System.out.println("result7가 참조하는 객체: "+ result7);
System.out.println(result7.x + ", " + result7.y);
}
}
result5가 참조하는 객체: day9.SampleValue@5e91993f
10, 20
result6가 참조하는 객체: day9.SampleValue@1c4af82c
100, 200
result7가 참조하는 객체: day9.SampleValue@379619aa
500, 620
- public class SampleApp2 {
public static void main(String[] args) { // 메인메소드
Sample sample = new Sample(); // 스택의 메인메소드 공간 안에 sample 참조변수(+주소값)가 들어있음
이 변수가 참조하는 Sample 객체에는 위의 내용들이 들어가 있음. - SampleValue result = sample.createSampleValue(10, 20);
// sample변수가 참조하는 객체 안에 있는 createSampleValue 메소드 호출 -> 스택에 메소드 저장공간 생성
- < createSampleValue 메소드 >
public class Sample { // create메소드를 갖고있는 객체
public SampleValue createSampleValue(int num1, int num2) { // create메소드 선언부
SampleValue sampleValue = new SampleValue();
// 반환타입 객체(SampleValue) 객체를 생성하고, 생성된 객체의 주소값을 참조변수 sampleValue에 대입
( = 참조변수sampleValue와 객체 SampleValue 연결 )
sampleValue.x = num1;
sampleValue.y = num2;
return sampleValue;
// 참조변수에 저장된 주소값(SampleValue객체의 주소값) 반환. 이 반환값이 메소드를 호출한 result변수로 감
}
} // 메소드 종료
∴ sample.createSampleValue(10.20); 메소드의 결과값 = sampleValue가 참조하고 있는 객체의 주소값
∴ createSampleValue메소드를 호출하면 SampleValue타입의 반환값을 얻는거
- < createSampleValue 메소드 >
- 메소드를 실행하고 난 반환값(주소값)을 result 변수에 대입 -> 메소드 종료
-> result 안에는 여전히 SampleValue객체의 주소값이 있음
-> 메소드를 호출하면 SampleValue객체 (반환타입 객체)의 주소값을 얻게 되는구나 - System.out.println(result.x); // 반환타입 객체의 x값 = 10
System.out.println(result.y); // 반환타입 객체의 y값 = 20
3. 메소드 중복정의 (Overloading)
- 하나의 클래스 안에 같은 이름의 메소드를 여러개 중복정의
ex) println 메소드 (타입별로 정의) - 매개변수의 타입 or 개수가 달라야함
- 자바가상머신은 메소드 호출시 전달받은 매개변수 인자들을 분석해서 중복정의된 메소드 중에서 매개변수의 타입과 개수가 일치하는 메소드를 자동으로 실행
메소드 중복정의의 목적
비슷한 작업은 일관되게 하나의 이름으로 실행하자
- 메소드 중복정의
public class Sample2 {
// 같은 클래스 안에 같은 이름의 메소드 여러개 가능-> 중복정의
// 매개변수의 타입, 개수가 달라야함
public int plus(int x, int y) {
System.out.println("정수 + 정수");
int z = x + y;
return z;
}
//매개변수의 타입, 개수는 같고 매개변수의 이름만 다르면 오류
// public int plus(int a, int b) {
// int c = a + b;
// return c;
// }
//매개변수의 타입이나 개수가 달라야 함 !
public double plus(int a, double b) {
System.out.println("정수 + 실수");
double c = a + b;
return c;
}
public int plus(int a, int b, int c) {
System.out.println("정수 + 정수 + 정수");
int d = a + b + c;
return d;
}
public double plus(double x, double y) {
System.out.println("실수 + 실수");
double z = x + y;
return z;
}
}
- 메소드 중복정의 활용
public class SampleApp3 {
public static void main(String[] args) {
//메소드 중복정의 활용
Sample2 sample = new Sample2();
sample.plus(10, 20);
sample.plus(10.5, 20);
sample.plus(10, 20.8);
sample.plus(10, 20, 30);
sample.plus(10.7, 20.8);
}
}
정수 + 정수
실수 + 실수
정수 + 실수
정수 + 정수 + 정수
실수 + 실수
실습)
* 반환타입이 int 등이야
그러면 일단 int 타입의 변수를 만들어놔
그리고 안에서 계산한 값을 int 변수 안에 저장을 하고
return 값은 그 int 변수로 설정해
- 메소드
public class Sample3 {
/*1.
* 정수 2개를 전달받아서 그 합계를 화면에 출력하는 메소드
* 반환타입 : void
* 메소드명 : plus
* 매개변수 : int x, int y
*/
public void plus(int x, int y) {
int z = x + y;
System.out.println("합계: "+ z);
}
/*2.
* 정수 2개를 전달받아서 더 큰 정수를 반환하는 메소드
* 반환타입 : int
* 메소드명 : max
* 매개변수 : int x, int y
* if문을 사용해서 구현하세요
*/
public int max(int x, int y) {
if(x >= y) {
return x;
} else {
return y;
}
}
/*3.
* 정수 3개를 전달받아서 더 큰 정수를 반환하는 메소드
* 반환타입 : int
* 메소드명 : max
* 매개변수 : int x, int y, int z
* if문을 2번 사용해서 구현하세요
*/
public int max(int x, int y, int z) {
int max = x; // 먼저 x가 크다고 정해
if (y > x) { // 근데 y가 x보다 크면
max = y; // max가 y로 바뀜
}
if (z > max) { // 둘 중 큰수보다 z가 크면
max = z; // max가 z로 바뀜
} // max가 더 크다면, 위 if문에서 해결됨
return max;
}
/*4.
* 정수 2개를 전달받아서 첫번째 정수부터 두번째 정수사이 정수들의 합계를 반환하는 메소드
* 반환타입 : int
* 메소드명 : sum
* 매개변수 : int start, int end
* for문을 사용해서 구현하세요. 합계를 저장할 변수를 먼저 정의하세요
*/
public int sum(int start, int end) {
int total = 0;
for(int i=start; i<=end; i++) {
total += i;
}
return total;
}
/*5.
* 정수배열 객체를 전달받아서 배열객체에 저장된 정수의 총합을 반환하는 메소드
* 반환타입 : int
* 메소드명 : sum
* 매개변수 : int[] numbers
* 향상된 for문을 사용해서 구현하세요. 합계를 저장할 변수를 먼저 정의하세요
*/
public int sum(int[] numbers) { //배열객체의 주소값을 sum메소드에 저장하고,그러면 numbers변수도 그 주소값을 참조하게 됨
int total = 0;
for(int number : numbers) {
total += number;
}
return total;
}
/*6.
* 정수 2개를 전달받아서 첫번째 정수부터 두번째 정수 사이의 숫자들이 저장된 배열객체를 반환하는 메소드
* 반환타입 : int[] (정수가 여러개 저장된 배열객체의 주소값을 반환한다)
* 메소드명 : createArray
* 매개변수 : int begin, int end
* 첫번째 정수와 두번째 정수도 포함됩니다. 두 정수를 이용해서 배열의 크기를 먼저 구하고, 그 크기만큼 배열을 생성하세요.
* for문을 사용해서 배열의 0번째부터 값을 저장하세요.
*/
public int[] createArray(int begin, int end) {
int size = (end - begin)+1; //배열 크기
int[] arr1 = new int[size]; //배열 생성
for(int index=0; index<size; index++) { //배열의 0번째부터 값 저장
arr1[index]=begin+index;
}
return arr1;
}
}
public class SampleApp4 {
public static void main(String[] args) {
Sample3 sample = new Sample3();
//1. void plus(int x, int y) 실행
sample.plus(3, 5);
sample.plus(432, 495);
//2. int max(int x, int y) 실행
int max = sample.max(3, 5);
int max2 = sample.max(-5, 0);
System.out.println("둘 중 큰 값: "+max);
System.out.println("둘 중 큰 값: "+max2);
//3. int max(int x, int y, int z) 실행
int max3 = sample.max(3, 7,10);
int max4 = sample.max(-2,-32,-6);
int max5 = sample.max(10,10,10);
System.out.println("셋 중 큰 값: "+max3);
System.out.println("셋 중 큰 값: "+max4);
System.out.println("셋 중 큰 값: "+max5);
//4. int sum(int start, int end) 실행
int total = sample.sum(2, 5);
int total2 = sample.sum(-10, -1);
System.out.println("두 정수 사이의 총합: "+total);
System.out.println("두 정수 사이의 총합: "+total2);
//5. int sum(int[] numbers) 실행
int[] arr1 = {10, 20, 30, 40};
int[] arr2 = {1, 3, 5, 7, 9};
int arrTotal = sample.sum(arr1);
int arr2Total = sample.sum(arr2);
System.out.println("정수배열 내 정수총합: "+arrTotal);
System.out.println("정수배열 내 정수총합: "+arr2Total);
//6. int[] createArray(int begin, int end) 실행
int[] arr3 = sample.createArray(2, 5);
int[] arr4 = sample.createArray(1000, 2000);
System.out.println(Arrays.toString(arr3)); //배열객체 안에 있는 값들을 보여줌
System.out.println(Arrays.toString(arr4));
}
}
'수업내용 > Java' 카테고리의 다른 글
[2022.09.17.토] 숙제1 (0) | 2022.09.18 |
---|---|
[2022.09.16.금] 생성자, this (0) | 2022.09.17 |
[2022.09.14.수] 메소드 (0) | 2022.09.14 |
[2022.09.13.화] 객체지향(클래스,객체) (0) | 2022.09.13 |
[2022.09.08.목] 배열 (0) | 2022.09.08 |