public class Playlist
{
String title;
String genre;
Boolean privatePlaylist = true;
Song[] listOfSongs;
public Playlist(String tl, String gn, Boolean priv)
{
tl = title;
gn = genre;
priv = privatePlaylist;
}
Song[] mostPlayedSongs()
{
return listOfSongs;
}
}
Above is my code. I am trying to create a java class that returns a playlist. I want it to return a title, genre, whether the playlist is private or public. All three of these things are already constructed above. However, to that list, as a fourth property I would like to add an array that lists all the song in the playlist. The array is already a property I created above(Song[]listOfSongs). However, I do not know how to join this array to the other three properties and how to put the songs in this array. Any suggestions?
if you don't want to change the songs, you could just place it in the constructor:
public PlayList(String title, String genre, Boolean privatePlaylist, Song[] songs) {
this.title = title;
this.genre = genre;
this.privatePlaylist = privatePlaylist; //original constructor wasn't assigning this property
this.listOfSongs = listOfSongs;
}
if the list of songs shouldn't be added in the constructor (i.e, it needs to be updated) I would use an ArrayList so you can change the size:
// Field:
private ArrayList<Song> listOfSongs;
// Constructor
public PlayList(String title, String genre, Boolean privatePlaylist) {
this.title = title;
this.genre = genre;
this.privatePlaylist = privatePlaylist; //original constructor wasn't assigning this property
this.listOfSongs = new ArrayList<>();
}
// To edit the songs:
public void setListOfSongs (ArrayList<Song> listOfSongs) {
this.listOfSongs = listOfSongs;
}
import java.util.ArrayList;
public class Playlist {
public final String title;
public final String genre;
public final Boolean privatePlaylist;
public final ArrayList<Song> listOfSongs;
public Playlist(String tl, String gn, Boolean priv) {
title = tl;
genre = gn;
privatePlaylist = priv;
listOfSongs = new ArrayList<>();
}
}
Example usage:
public class Main {
public static void main(String[] args) {
Playlist pl = new Playlist("title", "genre", false);
pl.listOfSongs.add(...);
System.out.println(pl.title);
}
}
Related
Related to my previous thread, i want to print an output like this:
bookId = "1234" (String)
bookName = "Machine Learning" (String)
price = $20 (int)
ratings = (array of object)
rater = a, score = 5
rater = b, score = 3
But this time, i tried to use an OOP manner.
So first, i made a POJO class called ProductView, the class will be look like this:
public class ProductView {
// field
private String bookId;
private String bookName;
private int price;
private List<Ratings> ratings;
// a constructor i tried to make
public ProductView(String bookId, String bookName, int price, List<Ratings> ratings) {
this.bookId = bookId;
this.bookName = bookName;
this.price = price;
this.ratings = ratings;
}
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.itemId = itemId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Ratings getRatings() {
return ratings;
}
public void setRatings(Ratings ratings) {
this.ratings = ratings;
}
}
After that, i made a class called Ratings with the following field:
public class Ratings {
private String rater;
private int score;
public Ratings(String rater, int score) {
this.rater = rater;
this.score = score;
}
}
And finally, i made a Main Class called Main:
public class Main {
public static void main(String[] args) {
}
}
In the Main Class, i want to create an instance of the ProductView class and give it some value.
But i don't know how to do it with a list object param in my constructor.
Anyone can give me some insight?
first:
List is an interface, you should pass an implementation of list such as ArrayList or similar
second:
you have a compilation error in ProductView -> SetBookId, in this.itemId you don't have itemId as member or constructor parameter
furthermore, in get/set rating you need to pass and return list of Ratings.
nameing:
Ratings is actually just a Rating, you can make a new class of List or just use the Rating as is but change the name
now for your Question:
you can initialize first the list with objects and then send it to the constructor
such as:
List<Ratings> ratings = new ArrayList<>();
ratings.add(new Ratings("rater",5));
ratings.add(new Ratings("rater2",6));
ProductView productView = new ProductView("bookId","bookName",1,ratings);
Or, just initialize the ArrayList in the Constructor, the first way is preferable:
ProductView productView1 = new ProductView("bookId","bookName",1,
new ArrayList<Ratings>(Arrays.asList(new Ratings("rater",5), new Ratings("rater2",6))
));
hopefully, this answers your question
same as DodgyCodeException mentioned in the comments.
I am trying to read a file, in to an array of objects, from my Movie class and then print the results.
public class Movie_Class {
private int MovieID;
private String MovieTitle;
private String Director;
private String Writer;
private String Duration;
private String Genre;
private String Classification;
private String ReleaseDate;
private Double Rating;
public Movie_18512117(int ID, String Title, String Mdirector, String Mwriter,
String Mduration, String Mgenre, String Mclassification, String MreleaseDate, Double Mrating) {
MovieID = ID;
MovieTitle= Title;
Director= Mdirector;
Writer= Mwriter;
Duration= Mduration;
Genre= Mgenre;
Classification= Mclassification;
ReleaseDate= MreleaseDate;
Rating= Mrating;
}
public int getMovieID(){
return MovieID;
}
public String getMovieTitle(){
return MovieTitle;
}
public String getDirector(){
return Director;
}
public String getWriter(){
return Writer;
}
public String getDuration(){
return Duration;
}
public String getGenre(){
return Genre;
}
public String getClassification(){
return Classification;
}
public String getReleaseDate(){
return ReleaseDate;
}
public Double getRating(){
return Rating;
}
public void setMovieID(int MovieID) {
this.MovieID = MovieID;
}
public void setMovieTitle(String MovieTitle){
this.MovieTitle = MovieTitle;
}
public void setDirector(String Director) {
this.Director = Director;
}
public void setWriter(String Writer) {
this. Writer = Writer;
}
public void setDuration(String Duration) {
this. Duration = Duration;
}
public void setGenre(String Genre) {
this.Genre = Genre;
}
public void setClassification(String Classification){
this.Classification = Classification;
}
public void setReleaseDate(String ReleaseDate){
this.ReleaseDate = ReleaseDate;
}
public void setRating(Double Rating){
this.Rating = Rating;
}
}
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class movie {
public static void main(String[] args) throws FileNotFoundException {
File myFile = new File ("movieLibrary.txt");
Scanner inputFile = new Scanner(myFile);
String str;
Movie_Class[] movie = new Movie_Class[100];
String[] tokens;
while (inputFile.hasNext()){
str=inputFile.next();
tokens = str.split(",");
for(int i = 0; i < movies.length; i++){
movie[i] = new Movie_18512117(1);
//I don't know how to read the lines in to //my array and split the spaces, then print the result.
System.out.println(movie);
}
}
inputFile.close();
}
}
try using the BufferedReader and FileReader classes instead of scanner if you want to iterate through an input stream like you do. In the link is an useful tutorial how to do this:
https://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
also, you can use the ".split(regex)" methode to further processes the incoming information from the file.
(e.g. split on spaces with String.split("\s+");)
As for adding to the information to the array; you could try ussing an ArrayList and its .add() methode instead of the object Array your using now.
Your constructor method for Movie_Class should be public Movie_Class, not public Movie_18512117. That's first mistake. Read more about constructors.
Then you can create a new Movie_Class object by calling
movie[i] = new Movie_Class(...);
In the constructor, you have to input all the details of the movie, not just the ID. If you want to create a movie object with only ID, you should define a new constructor with only ID as the input value, like following
public Movie_Class (int ID) {
// Do whatever you want
}
You can use ArrayList instead of an Array, if you want to add objects, without knowing the exact number of elements you should store in it. Read about ArrayLists and other Collections here.
Try to fix these errors first. Then you can go on.
public class Song
{
private String title;
private String artist;
public Song (String Title, String Artist)
{
Title = title;
Artist = artist;
}
public String toString()
{
return (title +" "+ artist);
}
}
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class compactDisc
{
private Song[] arr = new Song[20];
private int numSongs = 0;
public compactDisc () throws IOException
{
int i=0;
File file = new File ("song.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()&& i<arr.length)
{
String Title = inputFile.nextLine();
String Artist = inputFile.nextLine();
arr[i] = new Song(Title,Artist);
i++;
}
numSongs = i;
}
public String toString()
{
String str = "";
for (int j = 0; j < numSongs; j++)
{
str += arr[j].toString();
}
return str;
}
}
import java.io.IOException;
import java.util.Scanner;
public class collection
{
public static void main(String[] args) throws IOException
{
compactDisc cd = new compactDisc();
System.out.println(cd);
}
}
This program is to display a list of songs and artist as a CD. The song class is the format of my prints, compactDisc class read a file that contains a list of songs and artists into an array, and main program prints them. However, when I run the program, it prints out null nullnull nullnull nullnull nullnull nullnull null instead of the actual list, and the direction seems correct. I wonder why that happens.
check this here in your Song class.
private String title;
private String artist;
public Song (String Title, String Artist) {
Title = title;
Artist = artist;
}
you are assigning the null values that are not initialized from your Song class into the parameter and hence your classvariables will never be filled.
It should rather look like this
public class Song {
private String title;
private String artist;
public Song (String title, String artist) {
this.title = title;
this.artist = artist;
}
}
Also by convention classes should start with a capital letter and variables should start with a small letter.
The problem is here
public Song (String Title, String Artist)
{
Title = title;
Artist = artist;
}
the parameter is Title but you're assigning title (which is null);
Change to:
title = Title;
artist = Artist;
The problem is in the Song class, as explained in (my) comments:
public Song (String Title, String Artist)
{
Title = title; // assigns this.title into local Title
Artist = artist; // assigns this.artist into local Artist
}
im trying to create a item for a list, to display on a listview some pictures.
The codes is the following:
public static List<Item> getItemList(List<Picture> pictures, Context context)
{
List <Item> items = new ArrayList<Item>();
for (int i = 0; i < pictures.size(); i++) {
Item item = new Item(pictures.get(i).getID(),pictures.get(i).getAddress(),pictures.get(i).getDescription(),pictures.get(i).getPath());
items.add(item);
}
return items;
}
What i'm trying to do in this is to create an item for each picture on database. (getDescription would be to get the picture description from a database handler, same for address and path)
However im getting the following error in the line where i use the "gets"
The constructor ClipData.Item(int, String, String, String) is undefined.
What could this be? Thank you!
Picture Class
public class Picture {
int _id;
String _name;
String _address;
String _description;
String _path;
// Empty constructor
public Picture(){
}
// constructor
public Picture(int id, String name, String _address, String _description, String _path){
this._id = id;
this._name = name;
this._address = _address;
this._description = _description;
this._path = _path;
}
// constructor
public Picture(String name, String _address, String _description){
this._name = name;
this._address = _address;
this._description = _description;
this._path = _path;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
public void setDescription(String description){
this._description = description;
}
public String getDescription(){
return this._description;
}
// getting phone number
public String getAddress(){
return this._address;
}
// setting phone number
public void setAddress(String phone_number){
this._address = phone_number;
}
public String getPath(){
return this._path;
}
public void setPath(String path){
this._path = path;
}
}
try to use for each loop
public static List<Item> getItemList(List<Picture> pictures, Context context)
{
List <Item> items = new ArrayList<Item>();
for (Picture pic:pictures) {
int id = pic.getID();
String address = pic.getAddress();
String desc= pic.getDescription();
String path= pic.getPath();
Item item = new Item(id ,address ,desc,path);
items.add(item);
}
return items;
}
I am trying to access some information that my program isnt letting me.
in my method "addTrack" it doesnt recognise the myTracklist object. how do i call myTracklist.count by using a method in the main class?
public class CD {
String art;
String tit;
public CD(String artist, String title){
art = artist;
tit = title;
tracklist myTracklist = new tracklist(100);
}
public static void main(String[] args) {
String mainArtist;
String mainTitle;
CD myCD = new CD("Awesomeguy", "AwesomeCDName");
mainArtist = myCD.getArtist();
System.out.println(mainArtist);
mainTitle = myCD.getTitle();
System.out.println(mainTitle);
myCD.display();
}
public String getArtist(){
String person;
person = art;
return person;
}
public String getTitle(){
String name;
name = tit;
return name;
}
public boolean addTrack(String trackinfo){
boolean result = false;
if (myTracklist.count < 100){
myTracklist.add(trackinfo);
result = true;
}
return result;
}
public int numTracks(){
int amount;
amount = myTracklist.count();
return amount;
}
public void display(){
System.out.println("Artist = "+ art);
System.out.println("Title = "+ tit);
tracklist.display();
}
}
here is my tracklist class
public class tracklist {
int length;
int numUsed;
String[] storage;
public tracklist(int size){
length = size;
numUsed = 0;
storage = new String[length];
}
public int count(){
return numUsed;
}
}
You've got scope problems in that you're declaring tracklist inside the CD constructor so that it only exists inside of the constructor and nowhere else. You must make it a field that is declared in the class for it to be usable at all the methods of the class.
So instead of
public class CD {
String art;
String tit;
public CD(String artist, String title){
art = artist;
tit = title;
tracklist myTracklist = new tracklist(100);
}
do
public class CD {
private String art;
private String tit;
private tracklist myTracklist; // declared
public CD(String artist, String title){
art = artist;
tit = title;
myTracklist = new tracklist(100); // initialized
}
// getter and setter methods of course.
It's a subtle but important distinction.
As an aside: you'll want to learn Java naming conventions so that others can more readily understand your code and your questions. Class names begin with an upper case letter.
As a second aside: don't have outside classes directly manipulate class fields. Use private fields and public getters and setters to allow the class to have more control over just what can be seen and what can be done.
it should be myTracklist.count() here:
if (myTracklist.count < 100){
Also:
String tit; // oh I love this object name!
tracklist myTracklist;
public CD(String artist, String title){
art = artist;
tit = title;
myTracklist = new tracklist(100);
}
Since you have declared it in your customer the "myTracklist" variable will only be visible in your constructor. Hence "addTrack" doesnt recognise the myTracklist object.
Declare it globally,
public class CD {
String art;
String tit;
tracklist myTracklist;
And initialize in the constructor as below.
myTracklist = new tracklist(100);
Keep the declaration of myTrackList outside the constructor. Like this:-
String tit;
tracklist myTracklist;
public CD(String artist, String title){
art = artist;
tit = title;
myTracklist = new tracklist(100);
}