- 더하는 로직을 메서드로 만들자.
- 1.메서드의 이름을 결정하자. 더하는 기능이 있으므로 'add'라고 한다.
- 2.메서드가 데이터를 받을 지 결정한다. 두 정수를 받아서 두 정수 사이의 모든 합을 구하는 메서드를 만들자. 메서드가 데이터를 받을 때 매개변수 리스트에서 받으며, 변수를 선언 해서 데이터를 받는다.
- 3.두 정수 사이의 총합을 구한 결과값을 반환하기로 결정하자.
package com.dream.method;
class SumMachine {
//메서드를 정의할 때 'public void 메서드명( ) { } 로 작성한다.
public int add(int start, int end) {
int total = 0; //로컬 변수(메서드 { }내부에 선언한 변수)는 초기화해야한다.
for(int i=start; i<=end; i++) {
total += i; //total = total + i;
}
return total;
}
}
public class MethodEx02 {
public static void main(String[] args) {
SumMachine sm = new SumMachine(); //객체 생성
Calculator cu = new Calculator();
int result = sm.add(10, 100000000);
System.out.println(result);
result = cu.multiplication(7, 9);
System.out.println(result);
}
}