JAVA
[JAVA] 메소드-3
HJLIM
2020. 9. 7. 22:05
//dan1, dan2를 args(인자)로 만들어 구구단 구현(method)
public class MethodEx3{
public static void methodA(int dan1, int dan2){ //반환값이 없는 methodA 생성 및 인자 int a, int b 정의
for(int j = dan1; j<=dan2; j++){
for(int i=1; i<=9; i++){
System.out.println(j + " * " + i + " = " + (j * i));
}
System.out.println();
}
}
public static void main(String[] args){
methodA(2, 7); //인자 2, 7 전달 및 호출
}
}
int dan1, int dan2에 각각 2와 7을 전달하여 2단부터 7단까지 구구단을 출력.
문제) 주어진 배열값 중 홀수단(구구단 홀수)을 출력하시오.
public class MethodEx4{
public static void main(String[] args){
int[] array = {2, 5, 7, 3};
method(array); //메소드 호출
}
public static void method(int[] array){
for(int i=0; i<array.length; i++){ //배열 array의 길이만큼 반복
for(int j=1; j<10; j++){
if(array[i] % 2 != 0){ //홀수만 출력하기 위해 2로 나눴을 때 0이 아닌 것 선별
System.out.print(array[i] + " * " + j + " = " + (array[i]*j));
}
}System.out.println();
}
}
}
배열 {2, 5, 7, 3}에서 홀수인 5, 7, 3인 홀수단이 정상적으로 출력되었다.