TestCastException
package Week13;
import java.awt.*;
/**
* 컴퓨터프로그래밍1
* 학번:202402697
* 이름:엄태은
*/
public class TestCastException {
public static void main(String[] args) {
Rectangle r = new Rectangle();
try{ casting(r);
} catch (Exception e) {
System.out.println("Class Casting Exception is handled in main !!");
}
}
static void casting(Shape s) throws Exception {
Circle c = (Circle) s;
}
}
class Shape{
}
class Rectangle extends Shape{
}
class Circle extends Shape{
}
static void casting(Shape s) throws Exception { Circle c = (Circle) s; } 에서 전달받은 Shape 타입의 객체 s를 Circle 타입으로 캐스팅하는데, 이때 예외 ‘ClassCastException’가 발생함.
TestNullPointerException
package Week13;
/**
* 컴퓨터프로그래밍1
* 학번:202402697
* 이름:엄태은
*/
class TestNullPointerException {
public static void main(String[] args) {
try {
MyDate md = null;
System.out.printf("%dyear %dmonth %dday\n", md.year, md.month, md.day);
} // null을 넣어줬기 때문에 객체가 없음(오류)
catch (Exception e) {
MyDate md = new MyDate();
System.out.printf("%dyear %dmonth %dday\n", md.year, md.month, md.day);
}
}
}
class MyDate {
int year = 2023;
int month = 6;
int day = 7;
}
TestTokenPrint
package Week13;
/**
* 컴퓨터프로그래밍1
* 학번:202402697
* 이름:엄태은
*/
import java.util.StringTokenizer;
public class TestTokenPrint {
public static void main(String[] args) {
String s = "of the people, by the people, for the people";
String token;
StringTokenizer st = new StringTokenizer(s," ,");
try {
while(true) {
token = st.nextToken();
System.out.println(token);
}
} catch(Exception e) {
}
}
}
MultiplyTest
package Week13;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* 컴퓨터프로그래밍1
* 학번:202402697
* 이름:엄태은
*/
public class MultiplyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
boolean Input = false;
System.out.print("Enter two numbers >>");
while (!Input) {
try {
int n = sc.nextInt();
int m = sc.nextInt();
System.out.println(n + "x" + m + "=" + n * m);
Input = true;
}
catch (InputMismatchException e) {
System.out.println("Not integer number, retry!!");
sc.nextLine();
System.out.print("Enter two numbers >>");
}
}
}
}
Input의 초기 값을 false로 설정 -> while문을 사용해 작업 실행 후 만약 오류없이 실행되면 Input값을 true 로 설정해서 while문을 종료시켜서 프로그램 종료. 만약 입력받은 값이 정수가 아니면 catch문 안에 있는 코드 실행하고
오류 없이 try문에서 while문을 끝내줄 때 까지 계속 실행
'학교 > 컴프1' 카테고리의 다른 글
컴프 실습 코드 정리 (Week12) (1) | 2024.06.11 |
---|---|
컴프 1 실습 코드 정리 (Week11) (0) | 2024.05.26 |
컴프 1 실습 코드 정리 (W9~W10) (0) | 2024.05.26 |
컴프 1 실습 코드 정리(W7) (0) | 2024.05.26 |
컴프 1 실습 코드 정리(W6) (0) | 2024.04.14 |