The 1st project with Mr, jin. I'm just memorizing List<String> and throw_20260608

JAEWOONG LEE·2026년 6월 8일
post-thumbnail

At first, one point is List -> songs.add(song);
and second is
if(song.trim().length() < 3) //노래 제목이 너무 짧음
{
//trim() : 문자열에서 앞/뒤에 있는 공백을 제거 합니다. 예) " foo "->"foo"
throw new IllegalArgumentException("올바른 제목을 입력하세요.");
}
songs.add(song); //리스트에 곡을 추가합니다.

if(index < 0 || index >= songs.size()) //잘못된 번호
{
throw new IllegalArgumentException("곡을 찾을 수 없습니다.");
}
songs.remove(index); //리스트에서 곡을 제거합니다.
--------------------------------so far, I guess important point--------

import java.util.ArrayList;
import java.util.List;

//데이터 (곡)을 다루는 객체
public class Playlist
{
//곡 목록 데이터
private List songs = new ArrayList<>(); //빈 상태

public Playlist()
{
// 샘플 곡 추가하기
addSong("Lately - Stevie Wonder");
addSong("Ordinary People - John Legend");
addSong("Man In The Mirror - Michael Jackson");
}

//모든 노래 가져오기 
public List<String> getAllSongs()
{
    return songs;
}

//입력받은 번호에 맞는  곡 가져오기 
public String getSongByNumber(int number)
{
    //번호로부터 인덱스를 구합니다. 
    int index = number - 1; //인덱스가 0부터 시작히기 때문에 1을 빼줍니다.
    if(index < 0 || index >= songs.size())  //인덱스의 범위가 올바른지 확인합니다. //리스트의 사이트보다 크거나 작으면 안된다. 
    {
        throw new IllegalArgumentException("곡을 찾을 수 없습니다.");
    }
    
    return songs.get(index);    //실제로 곡에 접근합니다. //겟 메서드  //get(인덱스) : 인덱스에 해당하는 요소를 반환합니다. 
}

//노래 추가하기
public void addSong(String song)    //song : 새로 추가할 노래 
{
    if(song.trim().length() < 3)    //노래 제목이 너무 짧음
    {
        //trim() : 문자열에서 앞/뒤에 있는 공백을 제거 합니다.  예)  " foo "->"foo"
        throw new IllegalArgumentException("올바른 제목을 입력하세요.");
    }
    songs.add(song);    //리스트에 곡을 추가합니다. 
}

//노래 제거 하기
public void removeSong(int number)  //number : 제거할 노래의 번호 
{
    //번호를 인덱스로 변환하는 과정 
    int index = number - 1;
    if(index < 0 || index >= songs.size())  //잘못된 번호 
    {
        throw new IllegalArgumentException("곡을 찾을 수 없습니다.");
    }
    songs.remove(index);        //리스트에서 곡을 제거합니다. 
}

}

profile
just for programming test

0개의 댓글