본문

Scanner

반응형

# Scanner


Scanner는 화면, 파일, 문자열과 같은 입력소스로부터 문자데이터를 읽어오는데 도움을 줄 목적으로 JDK1.5부터 추가되었다.
Scanner에는 다음과 같은 생성자를 지원하기 때문에
다양한 입력소스로부터 데이터를 읽을 수 있다.


Scanner (String source)

Scanner (File source)

Scanner (File source, String charsetName)

Scanner (InputStream source)

Scanner (InputStream source, String charsetName)

Scanner (Readable source)

Scanner (ReadableByteChannel source)

Scanner (ReadableByteChannel source, String charsetName)


입력받을 값이 숫자라면 nextLine()대신 nextInt() 또는 nextLong()과 같은 메서드를 사용할 수 있다.
Scanner에서는 이와 같은 메서드를 제공함으로써 입력받은 문자를 다시 변환하는 수고를 덜어준다.



화면으로부터 값을 입력받고 입력받은 값을 출력하는 예제이다. do-wjhile문을 이용해서 반복적으로 값을 입력받도록 했다.

Source 01) ScannerEx01.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package scannerEx;
 
import java.util.Scanner;
 
public class ScannerEx01 {
 
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in); // Scanner(InputStream source)
        String input = "";
        do {
            System.out.println("원하는 값을 입력하세요. 입력을 마치시려면 Q를 입력하세요.->");
 
            // 입력한 값을 라인 단위로 읽어온다.
            input = scan.nextLine();
            System.out.println("입력하신 값은  " + input + "입니다.");
        } while (!input.equalsIgnoreCase("Q"));
 
        System.out.println("프로그램을 종료합니다.");
    }
}
cs

Result)

1
2
3
4
5
6
7
8
9
10
원하는 값을 입력하세요. 입력을 마치시려면 Q를 입력하세요.->
123
입력하신 값은  123입니다.
원하는 값을 입력하세요. 입력을 마치시려면 Q를 입력하세요.->
456
입력하신 값은  456입니다.
원하는 값을 입력하세요. 입력을 마치시려면 Q를 입력하세요.->
q
입력하신 값은  q입니다.
프로그램을 종료합니다.
cs


data2.txt파일로부터 데이터를 읽어서 합과 평균을 계산하는 예제이다.
Source 02) ScannerEx02.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package scannerEx;
 
import java.io.File;
import java.util.Scanner;
 
public class ScannerEx02 {
 
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(new File("data2.txt"));
        int sum = 0;
        int cnt = 0;
 
        while (sc.hasNextLine()) {
            sum += sc.nextInt();
            cnt++;
        }
 
        System.out.println("sum = " + sum);
        System.out.println("average = " + (double) sum / cnt);
    }
}
cs

[data2.txt]
100
200
300
400
500

Result)
1
2
sum = 1500
average = 300.0
cs


- 라인별로 끊어서 데이터를 읽은 후 데이터 처리를 해야하는 경우
Source 03) ScannerEx03.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
package scannerEx;
 
import java.io.File;
import java.util.Scanner;
 
public class ScannerEx03 {
 
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(new File("data3.txt"));
        int cnt = 0;
        int totalSum = 0;
 
        while (sc.hasNextLine()) {
            String line = sc.nextLine();    // 라인별로 분리한 후
 
            // ','를 구분자로 하는 Scanner를 이용해서 각각의 데이터를 읽는다.
            Scanner sc2 = new Scanner(line).useDelimiter(",");
            int sum = 0;
 
            while (sc2.hasNextInt()) {
                sum += sc2.nextInt();
            }
 
            System.out.println(line + ", sum = " + sum);
            totalSum += sum;
            cnt++;
 
        }
    }
}
cs

[data3.txt]
100, 100, 100
200, 200, 200
300, 300, 300
400, 400, 400
500, 500, 500

Result)
1
2
3
4
5
100100100, sum = 100
200200200, sum = 200
300300300, sum = 300
400400400, sum = 400
500500500, sum = 500
cs


학생들의 성적을 계산하는 예제이다.
Student는 학생의 정보를 담기 위한 것이고 
Score는 학생의 정보인 Student를 저장하고 출력하기 위한 것이다.
Source 04) ScoreData.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
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
 
import javax.swing.text.AbstractDocument.LeafElement;
 
public class ScoreData {
 
    public static void main(String[] args) throws Exception {
        Score score = new Score();
        Scanner sc = new Scanner(new File("scoreData.txt"));
 
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            Scanner sc2 = new Scanner(line).useDelimiter(",");
 
            score.add(sc2.next(), sc2.next(), sc2.nextInt(), sc2.nextInt(), sc2.nextInt());
        }
 
        score.displayList();
    }
}
 
class Score {
    ArrayList record = new ArrayList();
    
    int koreanTotal = 0;
    int mathTotal = 0;
    int englishTotal = 0;
    
    // add메서드를 호출하면 Student 객체를 생성해서 ArrayList인 record에 저장한다.
    public void add(String name, String studentNo, int koreanScore, int mathScore, int englishScore) {
        Student s= new Student(name, studentNo, koreanScore, mathScore, englishScore);
 
        record.add(s);        // 여기서의 add() 메서드는 ArrayList의 add()메서드이다.
        koreanTotal += s.koreanScore;
        mathTotal += s.mathScore;
        englishTotal +=s.englishScore;
    }
 
    int getSubjectTotal() {
        return koreanTotal + mathTotal + englishTotal;
    }
    
    public void displayList() {
        if(record.size()==0){
            System.out.println("표시할 데이터가 없습니다.");
            return;
        }
        
        System.out.println("이름   번호   국어   수학   영어     총점");
        System.out.println("========================================");
        
        for(int i=0;i<record.size();i++){
            System.out.println((Student)record.get(i));
        }
        
        System.out.println("========================================");
        System.out.println(Student.format(""
                + record.size(), 2, Student.RIGHT) + "명 총점 : "
                + Student.format("" + koreanTotal, 5, Student.RIGHT)
                + Student.format("" + mathTotal, 6, Student.RIGHT)
                + Student.format("" + englishTotal, 6, Student.RIGHT)
                + Student.format("" + getSubjectTotal(), 8, Student.RIGHT)
                );
    }
}
 
class Student {
    final static int LEFT=0;
    final static int CENTER= 1;
    final static int RIGHT=2;
    
    String name="";
    String studentNo="";
    int koreanScore=0;
    int mathScore=0;
    int englishScore=0;
    
    public Student(String name, String studentNo, int koreanScore, int mathScore, int englishScore) {
        this.name=name;
        this.studentNo=studentNo;
        this.koreanScore=koreanScore;
        this.mathScore=mathScore;
        this.englishScore=englishScore;
    }
    
    int getTotal(){
        return koreanScore+mathScore+englishScore;
    }
 
    public String toString() {
        return format(name, 4, LEFT)
                + format(studentNo, 4, RIGHT)
                + format("" + koreanScore, 6, RIGHT)
                + format("" + mathScore, 6, RIGHT)
                + format("" + englishScore, 6, RIGHT)
                + format("" + getTotal(), 8, RIGHT);
    }
    
 // format메서드는 문자열 str을 주어진 크기(length)의 공간에 지정된 정렬방식(alignment)으로 채워 넣어서 반환하는 일을 한다.
 // length 크기의 result라는 char배열을 생성해서 공백으로 채운 다음에 System.arrayCopy()를 이용해서 문자열 str의내용이 담긴 
 // char배열 source를 복사해 넣으면 된다. 문자열 str이 복사될 위치는 정렬방식에 따라 달리진다. 
 // 만일 문자열 str의 크기가length보다 크면 문자열 str을 length만큼만 잘라서 반환한다.
    static String format(String str, int lengthint alignment) {
        int diff = length - str.length();
        if (diff < 0)
            return str.substring(0length);
 
  // char배열 source에 str 문자열의 내용을 담는다.
        char[] source = str.toCharArray();
        // length 크기의 result라는 char배열을 생성 후
  char[] result = new char[length];
 
        // 배열 result를 공백으로 채운다.
        for (int i = 0; i < result.length; i++) {
            result[i] = ' ';
        }
 
  // System.arrayCopy()를 이용해서 문자열 str의 내용이 담긴 char배열 source를 복사해 넣으면 된다.
        switch (alignment) {
        case CENTER:
            System.arraycopy(source, 0, result, diff / 2, source.length);
            break;
        case RIGHT:
            System.arraycopy(source, 0, result, diff, source.length);
            break;
        case LEFT:
        default:
            System.arraycopy(source, 0, result, 0, source.length);
        }
        return new String(result);
    }
}
cs

[scoreData.txt]
임승한,1,80,80,80
홍길동,2,100,100,100
황진이,3,90,90,70
이순신,4,80,90,80

Result)





- 출처 및 참고자료 : JAVA의정석(남궁성 저)


반응형

공유

댓글