Radio station KJAVA wants a class to keep track of recordings it plays. Create a class named Recording that contains fields to hold methods for setting and getting a Recording’s title, artist, and playing time in seconds. Save the file as Recording.java. b. Write an application that instantiates five Recording objects and prompts the user for values for the data fields. Then prompt the user to enter which field the Recordings should be sorted by—song title, artist, or playing time. Perform the requested sort procedure, and display the Recording objects. Save the file as RecordingSort.java.
If you have any problem with the program feel free to comment.
Recording.java
public class Recording {
//instance of the class
private String title, artist;
private int playtime;
//getters and setters
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public int getPlaytime() {
return playtime;
}
public void setPlaytime(int playtime) {
this.playtime = playtime;
}
}
RecordingSort.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
public class RecordingSort {
public static void main(String[] args) throws
IOException {
// for taking console input
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
Recording[] ar = new Recording[5];
// taking user inputs
for (int i = 0; i < 5; i++)
{
Recording obj =
new Recording();
System.out.print("Enter Title: ");
obj.setTitle(br.readLine());
System.out.print("Enter Artist: ");
obj.setArtist(br.readLine());
System.out.print("Enter Playtime: ");
obj.setPlaytime(Integer.parseInt(br.readLine()));
ar[i] = obj;//
storing it into the array
System.out.println();
}
// taking sortings choice from
user
System.out.println("1.
Title");
System.out.println("2.
Artist");
System.out.println("3.
Playtime");
System.out.print("Enter your
sorting choice: ");
int choice =
Integer.parseInt(br.readLine());
switch (choice) {
//according to user choice perform
sort using comparator
case 1:
Comparator<Recording> t = (i, j) -> {
return
i.getTitle().compareTo(j.getTitle());//sorting by title
};
Arrays.sort(ar,
t);
break;
case 2:
Comparator<Recording> a = (i, j) -> {
return
i.getArtist().compareTo(j.getArtist());//sorting by artist
};
Arrays.sort(ar,
a);
break;
case 3:
Comparator<Recording> p = (i, j) -> {
return i.getPlaytime() < j.getPlaytime() ? -1
: 1;//sorting by playtime
};
Arrays.sort(ar,
p);
break;
}
//showing output
System.out.println("List After
Sort");
for (Recording i : ar) {
System.out.println(i.getTitle() + " " + i.getArtist() + " " +
i.getPlaytime());
}
}
}
Output
Get Answers For Free
Most questions answered within 1 hours.