Advertisement
STANAANDREY

musiclib oop

Sep 21st, 2023
1,116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.stream.IntStream;
  3.  
  4. class Song {
  5.     private String title;
  6.     private String[] artists;
  7.  
  8.     public Song(String title, String[] artists) {
  9.         this.title = title;
  10.         this.artists = artists;
  11.     }
  12.  
  13.     @Override
  14.     public String toString() {
  15.         return "Song{" +
  16.                 "title='" + title + '\'' +
  17.                 ", artists=" + Arrays.toString(artists) +
  18.                 '}';
  19.     }
  20.  
  21.     public void play() {
  22.         System.out.println("Play " + this.toString());
  23.     }
  24.  
  25.     public String getTitle() {
  26.         return title;
  27.     }
  28. }
  29.  
  30. class MusicLib {
  31.     private List<Song> songs;
  32.  
  33.     public MusicLib() {
  34.         this.songs = new ArrayList<>();
  35.     }
  36.  
  37.     public void addSong(final Song song) {
  38.         songs.add(song);
  39.     }
  40.  
  41.     public void rmSong(int index) {
  42.         songs.remove(index);
  43.     }
  44.  
  45.     public List<Song> getSongs() {
  46.         return songs;
  47.     }
  48.  
  49.     public void playByTitle(final String title) {
  50.         IntStream intStream = IntStream.range(0, songs.size());
  51.         OptionalInt index = intStream.filter(i -> songs.get(i).getTitle().equals(title)).findFirst();
  52.         songs.get(index.getAsInt()).play();
  53.     }
  54.  
  55.     public void playRandom() {
  56.         final int size = songs.size();
  57.         if (size == 0) {
  58.             return;
  59.         }
  60.         var random = new Random();
  61.         int index = random.nextInt(size);
  62.         songs.get(index).play();
  63.     }
  64. }
  65.  
  66. public class Main {
  67.  
  68.     public static void main(String[] args) {
  69.         var musicLib = new MusicLib();
  70.         musicLib.addSong(new Song("Midnight Train to Georgia", new String[]{"Gladys Knight & the Pips"}));
  71.         musicLib.addSong(new Song("Stairway to Heaven", new String[]{"Led Zeppelin"}));
  72.         musicLib.addSong(new Song("Imagine", new String[]{"John Lennon"}));
  73.         musicLib.addSong(new Song("All by Myself", new String[]{"Eric Carmen"}));
  74.         musicLib.addSong(new Song("What'd I Say", new String[]{"Ray Charles"}));
  75.         musicLib.addSong(new Song("Walking in Memphis", new String[]{"Marc Cohn"}));
  76.         musicLib.addSong(new Song("In the Air Tonight", new String[]{"Phil Collins"}));
  77.  
  78.         musicLib.playByTitle("Imagine");
  79.         musicLib.playRandom();
  80.     }
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement