course/inflearn

[만들어 가면서 배우는 JAVA 플레이그라운드] 구구단 (2)

hjkim0502 2022. 7. 15. 18:34
  • 배열 활용
public class Gugudan {
    public static void main(String[] args) {
        int result[] = new int[9];
        // 계산 결과 배열에 저장
        for (int i = 0; i < result.length; i++) {
           result[i] = 2 * (i + 1);
        }

        // 배열에 저장된 값 출력
        for (int i = 0; i < result.length; i++) {
           System.out.println(result[i]);
        }

        result = new int[9];
        // 계산 결과 배열에 저장
        for (int i = 0; i < result.length; i++) {
           result[i] = 3 * (i + 1);
        }

        // 배열에 저장된 값 출력
        for (int i = 0; i < result.length; i++) {
           System.out.println(result[i]);
        }
    }
}
  • int[] result = new int[9] 도 가능
  • result = new int[9]로 자료형 선언하지 않고 변수 다시 쓰면 덮어쓰는 것
public class Gugudan {
    public static void main(String[] args) {
        for (int j = 2; j < 10; j++) {
            int result[] = new int[9];
            // 계산 결과 배열에 저장
            for (int i = 0; i < result.length; i++) {
               result[i] = j * (i + 1);
            }

            // 배열에 저장된 값 출력
            for (int i = 0; i < result.length; i++) {
               System.out.println(result[i]);
           }
        }
    }
}
  • 이중 for문으로 2~9단 모두 출력 (중복 제거)

 

  • 메소드 활용: 중복 제거
public class Gugudan {
	public static int[] calculate(int times) {
		int result[] = new int[9];
		for (int i = 0; i < result.length; i++) {
			result[i] = times * (i + 1);
		}
		return result;
	}
	
	public static void print(int[] result) {
		for (int i = 0; i < result.length; i++) {
			System.out.println(result[i]);
		}
	}

	public static void main(String[] args) {
		for (int i = 2; i < 10; i++) {
			int[] result = calculate(i);
			print(result);
		}
	}
}

 

  • 클래스 활용: 코드 관리
  • 클래스명은 대문자 시작, 메소드명은 소문자 시작이 관례
// Gugudan class
public class Gugudan {
	public static int[] calculate(int times) {
		int result[] = new int[9];
		for (int i = 0; i < result.length; i++) {
			result[i] = times * (i + 1);
		}
		return result;
	}
	
	public static void print(int[] result) {
		for (int i = 0; i < result.length; i++) {
			System.out.println(result[i]);
		}
	}
}

// GugudanMain class
public class GugudanMain {
	public static void main(String[] args) {
		for (int i = 2; i < 10; i++) {
			int[] result = Gugudan.calculate(i);
			Gugudan.print(result);
		}
	}
}

 

출처: https://www.inflearn.com/course/java-codesquad/unit/7203?tab=curriculum 

https://www.inflearn.com/course/java-codesquad/unit/7204?tab=curriculum 

https://www.inflearn.com/course/java-codesquad/unit/7205?tab=curriculum