달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
728x90
반응형

안드로이드 - 전화번호부 관리 프로그램

원본 출처: http://warmz.tistory.com/497

* 친구 부탁으로 간단하게 만든 전화번호부 관리 프로그램.


PDApplication.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package PD;
 
import java.io.IOException;
 
/**
 * represents the application itself. */
 
public class PDApplication {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // 실행시 전화번호부 파일 이름을 쓰지 않으면 에러 메세지 출력
        /*
        if (args.length == 0) {
            System.err.println("You must provide the name of the file"
                    + " that contains the phone directory.");
            System.exit(1);
        }
        */
        PhoneDirectory phoneDirectory = new PhoneDirectory();
        // 전화번호부 기능을 수행할 클래스 생성.
         
        try {
            phoneDirectory.loadData("pd.txt"); 
            // 파일로부터 저장된 연락처들을 읽어들인다.
        } catch (IOException e) {
            e.printStackTrace();
        }
         
        PDGUI phoneDirectoryInterface = new PDGUI();    // GUI 생성
        phoneDirectoryInterface.processCommands(phoneDirectory);
        // 전화번호부 기능을 활성화
    }
}


DirectoryEntry.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package PD;
 
/**
 * represent a pair of name and number.
 * 쌍으로 이루어진 이름과 전화번호를 나타내는 클래스. */
 
public class DirectoryEntry {
    private String name;
    private String number;
 
    /** 연락처를 추가하는 함수 */
    public DirectoryEntry(String name, String number) {
        this.name = name;
        this.number = number;
    }
 
    /** 이름을 반환하는 함수 */
    public String getName() {
        return name;
    }
 
    /** 전화번호를 반환하는 함수  */
    public String getNumber() {
        return number;
    }
 
    /** 전화번호를 수정하는 함수  */
    public void setNumber(String number) {
        this.number = number;
    }
}

 
PhoneDirectory.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package PD;
 
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
 
/**
 * represents the phone directory, i.e. collection of entries.
 * provides lookup, add, and remove operations
 * 전화번호부 기능을 수행하는 클래스.
 * 보기, 추가 , 삭제, 저장기능을 수행한다. */
 
public class PhoneDirectory {
    private static final int INITIAL_CAPACITY = 100;    // 최대 저장 갯수
    private int capacity = INITIAL_CAPACITY;            // 최대 저장 갯수 설정
    private int size = 0;                               // 현재 저장 갯수
    private DirectoryEntry[] theDirectory =
        new DirectoryEntry[capacity];               // 전화번호부를 생성
    private String sourceName = null;               // 전화번호부 파일
    private boolean modified = false;               // 전화번호부 수정 여부
 
    /** 파일에 기록된 전화번호부를 읽어오는 함수 */
    public void loadData(String sourceName) throws IOException {
        this.sourceName = sourceName;
        try {
            BufferedReader in =
                new BufferedReader(new FileReader(sourceName));
            // 'sourceName' 파일로부터 데이터를 읽어 버퍼(in)에 저장한다.
             
            String name, number;
            while ((name = in.readLine()) != null) {    // 끝까지 읽는다.
                if ((number = in.readLine()) == null) { // 전화번호 값이 null이면
                    break;                              // 중지
                }
                add(name, number);      // 연락처를 추가한다.
            }
            in.close();
        } catch (FileNotFoundException ex) {
            return;
        }
    }
 
    /** 연락처를 추가하거나 수정하는 함수 */
    public String addOrChangeEntry(String name, String number) {
        String oldNumber = null;
        int index = find(name);     // 이름으로 저장된 연락처를 찾는다.
         
        if (index > -1) {            // 해당 이름을 찾았으면
            oldNumber = theDirectory[index].getNumber();    // 기존 전화번호를 임시 변수에 저장하고
            theDirectory[index].setNumber(number);          // 새로운 전화번호를 저장한다.
        } else {                    // 해당 이름을 못 찾았으면
            add(name, number);      // 새로 추가한다.
        }
        modified = true;            // 수정여부를 true로 고침.
         
        return oldNumber;           // 기존 전화번호를 반환한다.
    }
 
    /** 저장된 전화번호를 보여주는 함수 */
    public String lookupEntry(String name) {
        int index = find(name);     // 'name'으로 검색한다.
        if (index > -1) {            // 찾았으면
            return theDirectory[index].getNumber(); // 전화번호를 반환한다.
        } else {
            return null;
        }
    }
 
    /** 수정(추가, 삭제)된 전화번호부를 저장하는 함수 */
    public void save() {
        if (modified) {         // 변경사항이 있다면
            try {
                PrintWriter out =
                    new PrintWriter(new FileWriter(sourceName));
                    // 파일을 열어 스트림을 생성
                 
                for (int i = 0; i < size; i++) {
                    if(theDirectory[i].getNumber() == null)
                        continue;
                    out.println(theDirectory[i].getName());
                    out.println(theDirectory[i].getNumber());
                }   // 기록한다.
                 
                out.close();            // 스트림을 닫는다.
                modified = false;       // 수정여부를 false로
            } catch (Exception ex) {
                System.err.println("Save of directory failed");
                ex.printStackTrace();
                System.exit(1);
            }
        }
    }
 
    /** 매개변수 name으로 저장된 연락처를 찾는 함수 */
    private int find(String name) {
        for (int i = 0; i < size; i++) {
            if (theDirectory[i].getName().equals(name)) {
                return i;   // 찾으면 i를 반환(i는 순서를 의미한다.)
            }
        }
        return -1// Name not found.(이름을 못 찾으면 -1을 반환)
    }
 
    /** 이름과 전화번호를 추가하는 함수 */
    private void add(String name, String number) {
        if (size >= capacity) {      // 현재 저장되어 있는 개수가 최대 저장 개수보다 크면
            reallocate();           // 저장 용량을 할당한다.(용량 증가)
        }
        theDirectory[size] = new DirectoryEntry(name, number); // 추가
        size++;     // 현재 저장 개수 증가
    }
 
    /** 용량이 가득찼을 경우 용량을 더 할당해주는 함수 */
    private void reallocate() {
        capacity *= 2;              // 최대 용량을 두배로 늘린다.
        DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
        // 임시 전화번호부 배열을 생성한다.
        System.arraycopy(theDirectory, 0, newDirectory, 0, theDirectory.length);
        // 기존 전화번호부 배열의 내용을 임시 전화번호부 배열에 복사한다.
        theDirectory = newDirectory;
        // 참조 변수(전화번호부 배열)에 용량이 증가된 임시 전화번호부 배열을 연결한다.
    }
 
    /** 연락처를 삭제하는 함수 */
    public void removeEntry(String name) {
        /**** EXERCISE ****/
        int index = find(name);
         
        if (index > -1) {
            theDirectory[index].setNumber(null);
            modified = true;
        }
    }
}

 
PDGUI.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package PD;
 
import javax.swing.JOptionPane;
 
/**
 * provides graphical user interface
 * GUI를 제공하는 클래스. */
 
public class PDGUI {
    private PhoneDirectory theDirectory = null;
 
    /** GUI를 표시하고, 전화번호부 기능을 수행하는 함수 */
    public void processCommands(PhoneDirectory thePhoneDirectory) {
        String[] commands = { "Add/Change Entry", "Look Up Entry",
                "Remove Entry", "Save Directory", "Exit" };
        theDirectory = thePhoneDirectory;   // 매개변수로 받아온 기능 수행 클래스를
                                            // 등록
        int choice;
         
        do {
            choice = JOptionPane.showOptionDialog(null, "Select a Command",
                    "PhoneDirectory", JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, commands,
                    commands[commands.length - 1]);
            // 다이얼로그 GUI를 정의. 옵션 버튼의 인덱스를 반환한다.
             
            switch (choice) {       // 옵션 버튼의 인덱스에 따라 수행
            case 0:
                doAddChangeEntry();
                break;
            case 1:
                doLookupEntry();
                break;
            case 2:
                doRemoveEntry();
                break;
            case 3:
                doSave();
                break;
            case 4:
                doSave();
                break;
            }
        } while (choice < commands.length - 1);
        System.exit(0);
    }
 
    /** 연락처를 추가하거나 수정하는 함수 */
    private void doAddChangeEntry() {
        String newName = JOptionPane.showInputDialog("Enter name");
        // 간단한 input 다이얼로그를 생성
        if (newName == null) {
            return; // Dialog was cancelled.(입력되지 않으면 input 다이얼로그 파괴)
        }
        String newNumber = JOptionPane.showInputDialog("Enter number");
        if (newNumber == null) {
            return; // Dialog was cancelled.
        }
        String oldNumber = theDirectory.addOrChangeEntry(newName, newNumber);
        String message = null;
        if (oldNumber == null) { // New entry.
            message = newName + " was added to the directory"
                    + "\nNew number: " + newNumber;
        } else { // Changed entry.
            message = "Number for " + newName + " was changed "
                    + "\nOld number: " + oldNumber + "\nNew number: "
                    + newNumber;
        }
        JOptionPane.showMessageDialog(null, message);
    }
 
    /** 저장된 연락처를 보여주는 함수 */
    private void doLookupEntry() {
        // Request the name.
        String theName = JOptionPane.showInputDialog("Enter name");
        if (theName == null) {
            return; // Dialog was cancelled.
        }
        String theNumber = theDirectory.lookupEntry(theName);
        String message = null;
        if (theNumber != null) { // Name was found.
            message = "The number for " + theName + " is " + theNumber;
        } else { // Name was not found.
            message = theName + " is not listed in the directory";
        }
        JOptionPane.showMessageDialog(null, message);
    }
 
    /**
     * Method to remove an entry. pre: The directory has been loaded with data.
     * post: The requested name is removed, modified is set to true.
     */
     
    /** 저장된 연락처를 삭제하는 함수 */
    private void doRemoveEntry() {
        /**** EXERCISE ****/
        String theName = JOptionPane.showInputDialog("Enter name");
        if(theName == null){
            return;
        }
        String theNumber = theDirectory.lookupEntry(theName);
        String message = null;
        if(theNumber != null){
            message = theName + ", " + theNumber +
            " was deleted in the directory";
            theDirectory.removeEntry(theName);      // 삭제
        } else {
            message = theNumber + " is not listed in the directory";
        }
        JOptionPane.showMessageDialog(null, message);
    }
 
    /**
     * Method to save the directory to the data file. pre: The directory has
     * been loaded with data. post: The current contents of the directory have
     * been saved to the data file.
     */
    private void doSave() {
        theDirectory.save();
    }
}

 


 

728x90
반응형
:
Posted by mapagilove