input.txt
John 23456778
James 55664477
Lee 98654345
Park 65902334
Kim 44445555
Kwonn 08655285
input.txt 라는 파일로부터 사람들의 이름과 전화번호를 입력받아 배열에 저장하고 출력한다
처음에는 Scanner inFile = new Scanner(new File("input.txt"));에 오류가 나타나는데, 보면 'Unhandled exception type FileNotFountException'이라는 메세지가 나타난다
만약 input.txt라는 이름의 파일이 없다면 어떻게 할 것인지를 지정해주지 않았기 때문에 발생한 오류.
try/catch로 예외처리를 해준다
file 데이터 읽기 기본 설정
//20
public static void main(String[] args) {
//file로 데이터 읽기
try {
// system.in 대신에 데이터 파일의 이름을 지정하고 File을 만든 후 그 파일에 대한 Scanner를 만든다
Scanner inFile = new Scanner(new File("input.txt")); //try안의 내용을 try하는 동안에
inFile.close();
} catch (FileNotFoundException e) { // FileNotFoundException이라는 예외가 발생하면
// 그 예외를 catch해서 이 안에서 예외처리를 해준다
System.out.println("No file");
System.exit(9);;
}
}
그 다음 입력받은 input.txt의 내용을 이름 알파벳 순서로 정렬해 출력하도록 해본다
입력받은 name과 number, count는 main메소드 만이 아니라 bubbleSort 메소드에서도 사용되므로 main 메소드 외부에 선언한다
하나의 메소드가 아니라 클래스 전체에서 사용될 데이터는 클래스의 멤버로 만드는게 좋다
static String [] name = new String [1000]; //임시로 배열의 크기를 최대 1000개로 잡는다
static String [] number = new String [1000];
static int n = 0; //사람 수 몇명인가
public static void main(String[] args) {
//file에서 데이터 가져와서 정렬해서 출력하기
try {
Scanner inFile = new Scanner(new File("input.txt")); //try안의 내용을 try하는 동안에
while(inFile.hasNext()) { //읽을게 남아있느냐 = file의 끝에 도달했는지 검사
name[n] = inFile.next(); //name 저장
number[n] = inFile.next(); //number 저장
n++;
}
inFile.close();
} catch (FileNotFoundException e) { // FileNotFoundException이라는 예외가 발생하면
// 그 예외를 catch해서 이 안에서 예외처리를 해준다
System.out.println("No file");
System.exit(9); //프로그램 종료
}
//정렬하기
bubbleSort(); // name, number, count가 클래스의 멤버라서 매개변수로 넘겨줄 필요 없다
for (int i = 0; i < n; i++) {
System.out.println(name[i] + ": " + number[i]);
}
}//
static void bubbleSort() {
for (int i = n-1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (name[j].compareTo(name[j+1]) > 0) { //str1과 str2를 비교할때는 equals사용
//name[j]가 name[j+1]보다 크다면
//swap
String tmp = name[j];
name[j] = name[j+1];
name[j+1] = tmp;
//번호도 함께 swap
tmp = number[j];
number[j] = number[j+1];
number[j+1] = tmp;
}
}
}
}
두 이름에 대해서 알파벳 순서를 어떻게 비교하는가?
String간의 사전식 순서는 String클래스가 제공하는 compareTo 메소드를 사용한다
두 String str1과 str2에 대해 str1.compareTo(str2)는 str1이 앞쪽 순서면 음수, 둘다 같으면 0, 뒤쪽 순서면 양수를 반환한다.
대소문자 구분없이 비교할 경우에는 compartToIgnoreCase 메소드를 사용한다