본문 바로가기
Project

구구단 출력 프로젝트 01 - 모델(Model) 만들기

by 보라코끼리 2021. 10. 7.
728x90
  • 만드려는 프로그램
    • 구구단 형태로 출력
    • 첫 단, 마지막 단, 마지막 곱할 수를 작성해서 계산을 누르면
    • 위와 같은 형태로 출력되도록 할 예정

 

/*
    firstTimes : 첫번째 단 (입력)
    lastTimes : 마지막 단 (입력)
    firstMultiplier : 첫번째 곱하는 수 (입력X -> 1로 고정)
    lastMultiplier : 마지막 곱하는 수 (입력)
*/

1) 2 * 1 = 2 형태의 문자열 리턴

private String generateTimesString(int times, int multiplier) {
    int result = times * multiplier;
    String timesString = times + " * " + multiplier + " = " + result;
    return timesString;		
}

2) 2 * 1 = 2, 2 * 2 = 4, 2 * 3 = 6 ... 형태의 문자열 배열을 리턴 -> 한 단

private String[] generateTimes(int times, int firstMultiplier, int lastMultiplier) {
    String[] time = new String[lastMultiplier+1];
    for (int i = firstMultiplier; i <= lastMultiplier; i++) {
    time[i] = generateTimesString(times, i);
    }
    return time;
}

3) 2차원 배열 형태로 리턴 -> ex) [2][1] 입력 시 2 * 1 = 2 형태로 반환되도록

public String[][] generateTimesTable(int firstTimes, int lastTimes, int firstMultiplier, int lastMultiplier) {
    String[][] timesTable = new String[lastTimes+1][];
    for (int i = firstTimes; i <= lastTimes; i++) {
    timesTable[i] = generateTimes(i, firstMultiplier, lastMultiplier);
    }
    return timesTable;
}

 

* 전체 코드

@Service
public class TimesTableService {

	private TimesTableService() {}

	// [2][1] -> 2 * 1 = 2 형태로 배열 반환
	public String[][] generateTimesTable(int firstTimes, int lastTimes, int firstMultiplier, int lastMultiplier) {
		String[][] timesTable = new String[lastTimes+1][];
		for (int i = firstTimes; i <= lastTimes; i++) {
			timesTable[i] = generateTimes(i, firstMultiplier, lastMultiplier);
		}
		return timesTable;
	}

	// 2 * 1 = 2, 2 * 2 = 4 형태의 문자열 배열 반환 -> 단
	private String[] generateTimes(int times, int firstMultiplier, int lastMultiplier) {
		String[] time = new String[lastMultiplier+1];
		for (int i = firstMultiplier; i <= lastMultiplier; i++) {
			time[i] = generateTimesString(times, i);
		}
		return time;
	}

	// 2 * 1 = 2 형태 문자열 반환
	private String generateTimesString(int times, int multiplier) {
		int result = times * multiplier;
		String timesString = times + " * " + multiplier + " = " + result;
		return timesString;		
	}
}
728x90