앞 포스팅과 다른점은 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("");
		}
	}
}
public class MainClass02 {
	public static void main(String[] args) {
		MultiplicationTable start = new MultiplicationTable();
		start.inputValue();
		start.outputResult();
//		start.outputResult2();
	}
}
import java.util.Scanner;

public class MultiplicationTable {
	int input1, input2;

	void inputValue() {
		// void inputValue() throws Exception{
		int chk = 0;
		while (chk != 1) {
			try {
				// 입력
				Scanner in = new Scanner(System.in);
				System.out.print("first value : ");
				this.input1 = in.nextInt();
				System.out.print("second value : ");
				this.input2 = in.nextInt();

				// 예외 발생시키기
				if ((input1 > input2)) {
					throw new Exception("\n첫번째 값은 뒷자리보다 작은 수를 입력하시오.\n");
				} else if ((input1 > 9) || (input2 > 9)) {
					throw new Exception("\n9 미만의 수를 입력하시오.\n");
				}

				// 예외가 일어나지 않아야 밑으로 이동
				chk = 1;
			} catch (Exception e) {
				System.err.println(e.getMessage());
				// System.err.println(e);
			}
		}
	}

	void outputResult() {
		for (int dan = input1; dan <= input2; dan += 3) {
			for (int line = 1; line < 10; line++) {
				System.out.printf(dan > input2 ? " " : "%d x %d = %2d  ", dan,
						line, (dan * line));
				System.out.printf(dan + 1 > input2 ? " " : "%d x %d = %2d  ",
						dan + 1, line, ((dan + 1) * line));
				System.out.printf(dan + 2 > input2 ? "\n" : "%d x %d = %2d\n",
						dan + 2, line, ((dan + 2) * line));
			}
			System.out.println("");
		}
	}
}

+ Recent posts