반응형

7.5>하나의 학생 정보를 Student 클래스로 표현한다. Student 클래스에는 이름, 학과, 학번, 학점 평균을 나타내는 필드가 있다. 키보드로 학생 정보를 5개 입력 받아  ArrayList<Student>에 저장한 후에 ArrayList<Student>의 모든 학생 정보를 출력하는 프로그램을 작성하라.


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
package SecondHW;
import java.util.*//Arraylist와 스캐너 사용 위한 임포트
class Student{ //Student 클래스, 스트링형 name, department, 정수형 number, double형 score 포함
    String name;
    String department;
    int number;
    double score;
    public Student(String name, String department, int number, Double score){
        this.name=name; //Studnet 클래스의 생성자 인자를 객체의 각 원소에 대입한다.
        this.department=department;
        this.number=number;
        this.score=score;
    }}
public class Roaster {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);  //스캐너 객체
        ArrayList<Student> st = new ArrayList<Student>(); //Student를 원소로 갖는 어레이리스트
        System.out.println("학생 정보를 입력하세요: ");
        for(int i=0;i<5;i++//5번 반복
        {
                System.out.print((i+1)+"이름>>");
                String name=s.nextLine();
                System.out.print((i+1)+"학과>>");
                String department=s.nextLine();
                System.out.print((i+1)+"학번>>");
                int number=s.nextInt();
                System.out.print((i+1)+"학점평균>>");
                double score=s.nextDouble();  //이름, 학과, 학번, 학점평균을 Scanner객체 s를 이용하여 받는다.
                Student tmp = new Student(name,department,number,score); //Student 객체 tmp 생성 
                st.add(tmp); //tmp를 st의 원소로 추가
                s.nextLine(); //버퍼에서 개행문자를 비워주기 위함
        }
        for(int i=0;i<st.size();i++){ //st.size=5이므로 5번 반복
            Student res = st.get(i); //어레이리스트 st에서 i번째 인덱스 원소를 res에 대입
            System.out.println("=============================");
            System.out.println("이름: "+res.name);
            System.out.println("학과: "+res.department);
            System.out.println("학번: "+res.number);
            System.out.println("학점평균: "+res.score);
            System.out.println("=============================");//각 원소 출력
        }}}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

제네릭 클래스  (0) 2017.06.19
학점 계산  (0) 2017.06.19
가장 큰 수  (0) 2017.06.19
겜블링 게임  (0) 2017.06.19
가위바위보  (0) 2017.06.19

+ Recent posts