[Java] 배열과 ArrayList - 예제

나영원·2020년 8월 30일
0

Java_basic

목록 보기
38/60

_ArrayList를 활용한 응용 프로그램

어느_학교에 학새잉 3명이 있고 각 학생마다 읽은 책을 기록하고 있습니다.
Student 클래스를 만들고 각 학생마다 읽은 책을 Student클래스 내에 ArrayList를 생성하여 관리하도록 합니다.
다음과 같이 출력 되도록 Student, Book, StudentTest 클래스를 만들어 실행하세요

//Book 클래스 생성
public class Book {
	
	public String title;
	public String author;
	
	public Book (String title,String author) {
		this.title=title;
		this.author=author;
		
	}

		public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getTitle() {
		
		return title;
	}

}
//Student 클래스 생성
import java.util.ArrayList;

public class Student {
	
	public String studentName;
	ArrayList<Book> bookList;
	
	public Student(String studentName) {
		this.studentName=studentName;
		
		
		bookList = new ArrayList<Book>();
		
	}
	
	public void addBook(String title, String author) {
		
		Book book = new Book(title, author);
		bookList.add(book);
	}
	
	public void showInfo() {
		System.out.print(studentName+"학생이 읽은 책은 : ");
		for(Book book : bookList) {
			System.out.print(book.getTitle()+" ");
		}
		System.out.println("입니다");
	}
	
}
//StudentTest 클래스 생성
public class StudentTest {

	public static void main(String[] args) {
		Student Lee = new Student("Lee");
		
		Lee.addBook("태백산맥1", "조정래");
		Lee.addBook("태백산맥2", "조정래");
		
		Student Kim = new Student("Kim");
		
		Kim.addBook("토지1", "박경리");
		Kim.addBook("토지2", "박경리");
		Kim.addBook("토지3", "박경리");

		Student Cho = new Student("Cho");
		
		Cho.addBook("해리포터1", "조앤 롤링");
		Cho.addBook("해리포터2", "조앤 롤링");
		Cho.addBook("해리포터3", "조앤 롤링");
		Cho.addBook("해리포터4", "조앤 롤링");
		Cho.addBook("해리포터5", "조앤 롤링");
		Cho.addBook("해리포터6", "조앤 롤링");
		
		Lee.showInfo();
		Kim.showInfo();
		Cho.showInfo();
	}

}

직전에 했던 예제와 같이 Student 인스턴스안에 Array List를 생성하고 그안에 Book 인스턴스들의 내용을 입력해서 담는 메서드를 만들고 showInfo 메서드를 통해 ArrayLIst안에 내용들을 출력하는 예제였습니다.

profile
배우는 개발 일기

0개의 댓글

관련 채용 정보