Transcript 실습 1

10장 예외
Lab 10-1
목차
 예외
 문자 개수 세기
 예외 처리
 파일 I/O
 텍스트 파일에 읽고 쓰기.
2
문자 개수 세기
 CountLetters를 실행해본다.
 공백과 다른 기호를 포함한 구문을 input으로
하여 실행해본다.
 ArrayIndexOutOfBoundException발생! Why?
 문자가 아닌 것을 처리할 수 있도록 메소드를
수정한다.
 첫 번째 for문의 body에 예외를 처리할 수 있도록
try-catch문을 작성한다.
 Catch문에서 문자가 아닌 것을 제외시킨다.
3
문자 개수 세기 Cont.
//*******************************************************
// CountLetters.java
//
// 사용자로부터 입력받은 단어의 각 문자 수를 세어 출력한다.
//*******************************************************
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
int[] counts = new int[26];
Scanner scan = new Scanner(System.in);
// 사용자로부터 단어를 입력받는다.
System.out.print("Enter a single word (letters only, please): ");
String word = scan.nextLine();
4
문자 개수 세기 Cont.
// 대문자로 변환한다.
word = word.toUpperCase();
// 각 문자의 개수를 센다.
for (int i = 0; i < word.length(); i++)
counts[word.charAt(i)-'A']++;
// 출력한다.
System.out.println();
for (int i = 0; i < counts.length; i++)
if (counts[i] != 0)
System.out.println((char)(i+'A') + ": " + counts[i]);
}
}
5
예외 처리
 ParseInts를 실행해본다.
 주어진 input으로 실행해본다.
 10, 20, 30, 40
 We have 2 dogs and 1 cat.
 NumberFormatException 발생!
 프로그램을 수정한다.
 While문 안에 try-catch문을 추가한다.
 Input에서 읽은 것이 정수가 아닐 때 에러를 발생
하지 않게 한다.
6
예외 처리 Cont.
//*******************************************************
// ParseInts.java
//*******************************************************
import java.util.Scanner;
public class ParseInts
{
public static void main(String[] args)
{
int val, sum = 0;
Scanner scan = new Scanner(System.in);
String line;
System.out.println("Enter a line of text");
Scanner scanLine = new Scanner(scan.nextLine());
while(scanLine.hasNext())
{
val = Integer.parseInt(scanLine.next());
sum += val;
}
System.out.println("The sum of the integers on this line is " + sum);
}
}
7
텍스트 파일 – 읽고 쓰기
 주석에 따라 프로그램을 완성한다.
 Input 파일로부터 스캐너 객체를 생성한다.
 FileWriter로부터 Printwriter 객체 outfile을 생
성한다.
 While의 body를 완성한다.
 이름, 총 이수시간, 총 이수학점을 읽어와 GPA를
계산한다.
 GPA = 총 이수학점/ 총 이수시간
 학사경고를 받아야 하는 학생이라면 이수시간과
GPA를 outfile에 저장한다. (공백으로 구분)
8
텍스트 파일 – 읽고 쓰기 Cont.
 학사 경고의 기준
- 총 이수시간이 30시간 미만인 경우  1.5
- 총 이수시간이 60시간 미만인 경우  1.75
- 그 외  2.0
 printWriter를 닫는다.
 발생할 수 있는 예외
 FileNotFoundException : inputfile이 없는 경우
 NumberFormatException : inputfile 형식에 오류
가 있는 경우
 IOException : 입력/출력 스트림에 문제가 있는 경우
 이 예외를 처리한다. 적절한 메시지를 출력하여 프로그램
을 종료 시킴.
9
텍스트 파일 – 읽고 쓰기 Cont.
//*******************************************************
// Warning.java
//
// 텍스트 파일에서 학생 정보를 읽고 다른 텍스트 파일에 정보를 쓴다.
//*******************************************************
import java.util.Scanner;
import java.io.*;
public class Warning
{
//--------------------------------------------------//
텍스트 파일에서 학생 정보를 읽어 GPA를 계산한다.
//
만약 학생이 학사 경고를 받아야 한다면
//
다른 텍스트 텍스트 파일에 저장한다.
//--------------------------------------------------public static void main(String[] args)
{
int creditHrs;
// 이수 시간
double qualityPts;
// 이수 학점
double gpa;
// 학점 평균
String line, name, imputName = "students.dat";
String outputName = "warning.dat";
10
텍스트 파일 – 읽고 쓰기 Cont.
try
{
// 스캐너를 구성한다.
// 출력 스트림을 구성한다.
// 출력 파일의 헤더를 출력
outFile.println();
outFile.println("Students on Academic Warning");
outFile.println();
// 입력 파일(텍스트 파일)을 읽는다.
while()
{
// 이수시간과 이수 학점으로 학사 경고 여부를 결정한다.
// 학사 경고를 받아야 한다면 그 학생의 정보를 출력
// 파일에 적는다.
}
11
텍스트 파일 – 읽고 쓰기 Cont.
// 출력 파일을 닫는다.
}
catch (FileNotFoundException exception)
{
System.out.println("The file " + inputName + " waw not found.");
}
catch (IOException exception)
{
System.out.println(exception);
}
catch (NumberFormatException e)
{
System.out.println("Format error in input file : " + e);
}
}
}
12