임얼쑤의 국어성적은77
임얼쑤의 수학성적은88
임얼쑤의 체육성적은99
총점은264
다음과 같이 Student의 과목 및 성적을 입력받고, 총점을 출력해보는 프로그램을 만들어 보려고 한다.
public class Student {
int studentNumber;
String name;
ArrayList<Subject> subjectArrayList;
...
과목이 SubjectEnglish, SubjectMath 와 같이 여러 변수가 생길 수 있기에 Subject로 따로 분리해서 관리한다.
이 때, Subject가 여러개 있을 수 있으므로 ArrayList로 관리한다.
public Student(int studentNumber,String name){
this.studentNumber=studentNumber;
this.name=name;
subjectArrayList = new ArrayList<>();
}
일단 생성자로 학생 이름과 번호를 받아준다.
그리고 학생을 생성할 때, subjectArrayList또한 생성해준다.
public void setSubject(String subjectName,int score){
Subject subject = new Subject(subjectName,score);
subjectArrayList.add(subject);
}
과목 이름, 점수 입력받고 ArrayList에 추가해준다.
public void showStudentInfo(){
int total = 0;
for(Subject subject : subjectArrayList){
total += subject.getScore();
System.out.println(name + "의" + " " + subject.getName() + "성적은" + subject.getScore());
}
System.out.println("총점은" + total);
}
for(Subject for(Subject subject : subjectArrayList)
여기가 이 글의 핵심
값을 출력할 때, Enhanced For loop을 이용하여, ArrayList의 값을 Subject subject에 집어넣어 출력한다.
그러면 Subject.getName()을 통해 각각의 값을 가져올 수 있다.
※ 배열은 Array.length를 하면 전체 길이가 출력되는 반면에 ArrayList는 ArrayList.size()를 하면 가지고 있는 값의 크기만큼만 출력이 된다.
ArrayList<String> test = new ArrayList<>();
test.add("hi");
test.add("bye");
for(int i=0; i<test.size();i++){
String str = test.get(i);
System.out.println(str);
}
출력결과:
hi
bye
ㅡㅡㅡㅡㅡㅡㅡㅡ ↓전체코드 ㅡㅡㅡㅡㅡㅡㅡㅡ
public class MainTest {
public static void main(String args[]){
Student student = new Student(1001,"임얼쑤");
student.setSubject("국어",77);
student.setSubject("수학",88);
student.setSubject("체육",99);
student.showStudentInfo();
}
}
메인코드
import java.util.ArrayList;
public class Student {
int studentNumber;
String name;
ArrayList<Subject> subjectArrayList;
public Student(int studentNumber,String name){
this.studentNumber=studentNumber;
this.name=name;
subjectArrayList = new ArrayList<>();
}
public void setSubject(String subjectName,int score){
Subject subject = new Subject(subjectName,score);
subjectArrayList.add(subject);
}
public void showStudentInfo(){
int total = 0;
for(Subject subject : subjectArrayList){
total += subject.getScore();
System.out.println(name + "의" + " " + subject.getName() + "성적은" + subject.getScore());
}
System.out.println("총점은" + total);
}
}
Student 전체코드
public class Subject {
String name;
int score;
public Subject(String name,int score){
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
Subject 코드
'정리하기 이전 자료 ( before 20-11 ) > Java' 카테고리의 다른 글
상속에서의 생성자 (0) | 2020.03.29 |
---|---|
다형성 , 상속, 가상함수 , 동적바인딩 (0) | 2020.03.28 |
배열 ( Array ) (0) | 2020.03.27 |
Singleton Pattern (0) | 2020.03.25 |
Call by value VS Call by reference (0) | 2020.03.25 |
댓글