3. 아래의 객체를 예를 들어 설명하시오.
-ClassCastException
-NullPointerException
-ArrayIndexOutOfBoundsException
class Parent {
Parent() {
}
}
class Child extends Parent {
Child() {
}
}
class Print {
Print() {
}
private static StringBuilder print = new StringBuilder();
static void printClassCastExceptionOccur() {
print.append("ClassCastException occurs.");
printlnAndReset();
}
static void printNullPointerExceptionOccur() {
print.append("NullPointerException occurs.");
printlnAndReset();
}
static void printArrayIndexOutOfBoundsExceptionOccur() {
print.append("ArrayIndexOutOfBoundsException occurs.");
printlnAndReset();
}
private static void printlnAndReset() {
System.out.println(print);
print.setLength(0);
}
}
class Exceptions {
public static void main(String[] args) {
try {
Parent parent = new Parent();
Child childFromParent = (Child)parent;
} catch(ClassCastException e) {
Print.printClassCastExceptionOccur();
}
try {
String str = null;
str.length();
} catch(NullPointerException e) {
Print.printNullPointerExceptionOccur();
}
try {
boolean[] booleans = new boolean[0];
booleans[0] = true;
} catch(ArrayIndexOutOfBoundsException e) {
Print.printArrayIndexOutOfBoundsExceptionOccur();
}
}
}
//
//print
//
ClassCastException occurs.
NullPointerException occurs.
ArrayIndexOutOfBoundsException occurs.
4. 아래의 결과를 나타내는 사칙연산 계산기를 완성하시오.
interface ICalculator {
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);
}
public class CalculatorMain {
public static void main(String[] args) {
Calculator cal = new Calculator();
System.out.println(cal.add(6, 5));
System.out.println(cal.sub(6, 5));
System.out.println(cal.mul(6, 5));
System.out.println(cal.div(6, 0));
}
}
class Print {
Print() {
}
private static StringBuilder print = new StringBuilder();
static void exitCalculator() {
print.append("계산기 종료");
System.out.println(print);
print.setLength(0);
}
}
class Calculator implements ICalculator {
Calculator() {
}
@Override
public int add(int x, int y) {
return (x + y);
}
@Override
public int sub(int x, int y) {
return (x - y);
}
@Override
public int mul(int x, int y) {
return (x * y);
}
@Override
public int div(int x, int y) {
int result = -1;
try {
result = (x / y);
} catch(ArithmeticException e) {
e.printStackTrace();
Print.exitCalculator();
System.exit(0);
}
return result;
}
}
//
//print
//
11
1
30
java.lang.ArithmeticException: / by zero
at Calculator.div(CalculatorMain.java:34)
at CalculatorMain.main(CalculatorMain.java:51)
계산기 종료