앞 포스팅과 다른점은 try-catch 위치 변경.
package Test03;
class MainClass {
public static void main(String[] args) {
// 객체 생성, 메서드 호출, for한번 허용
MultiplicationTable play = new MultiplicationTable();
for (int chk = 0; chk != 1;) {
try {
chk = play.inputValue(chk);
play.outputResult();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
package Test03;
import java.util.Scanner;
class MultiplicationTable {
int input_first, input_last;
int inputValue(int chk) throws Exception {
// 입력
Scanner in = new Scanner(System.in);
System.out.print("구구단의 시작단을 입력하세요 ");
this.input_first = in.nextInt();
System.out.print("구구단의 마지막단을 입력하세요 ");
this.input_last = in.nextInt();
// 예외 발생시키기
if (input_first > input_last) {
throw new Exception("시작단은 마지막단보다 작아야합니다.");
}
if ((input_first < 2) || (input_last > 9)) {
throw new Exception("구구단은 2~9단을 입력하세요.");
}
// 예외가 일어나지 않아야 밑으로 이동
chk = 1;
return chk;
}
void outputResult() {
for (int dan = input_first; dan <= input_last; dan += 3) {
for (int line = 1; line < 10; line++) {
System.out.printf(dan > input_last ? " " : "%d x %d = %2d ",
dan, line, (dan * line));
System.out.printf(dan + 1 > input_last ? " "
: "%d x %d = %2d ", dan + 1, line, ((dan + 1) * line));
System.out.printf(dan + 2 > input_last ? "\n"
: "%d x %d = %2d\n", dan + 2, line, ((dan + 2) * line));
}
System.out.println("");
}
}
}
'대학 생활 > JAVA' 카테고리의 다른 글
| [JAVA] * 별 출력하기_09 마름모 (0) | 2013.11.14 |
|---|---|
| [JAVA] 스무고개 만들기 (0) | 2013.10.28 |
| [JAVA] 구구단 3단씩 출력(try-catch 사용)_01 (0) | 2013.10.08 |
| [JAVA] * 별 출력하기_08 모래시계 (4) | 2013.10.04 |