RarkMowe
RarkMowe

Reputation: 77

How to write contents of an array list to a text file?

I have this basic enough Java program that asks the user to input songs to a music library array list. From there the user can shuffle their songs, delete a song, delete all etc. It's nearly finished, I just have one issue I can't resolve. It happens when I try export the array list to a text file. Instead of the content of the array list, my output would look like this, as opposed to the details the user submitted:

"1: MainClass.SongClass@c137bc9 MainClass.SongClass@c137bc9"

I'll post my code below, I'd really appreciate if someone could point me in the right direction!

My Final Project class which serves as my main class:

package MainClass;

import java.io.FileNotFoundException;
import java.util.Scanner;

public class FinalProject extends UserInput {

    public String nextInt;

    public static void main(String[] args) {

//        SongLibrary iTunes;  //Object stores the file cars.txt
//        iTunes = new SongLibrary("MUSIC LIBRARY.txt");
//        songData CLO = iTunes.readFileIntoList();

        UserInput ui;
        ui = new UserInput();

        Scanner input = new Scanner(System.in);

        int opt;



        //Calls Methods Class so methods can be used below
        Menu menuFunctions = new Menu();

        //Calls FileReaderTest Class so file can be read
        SongLibrary Reader = new SongLibrary();

        //initial prompt only displayed when program is first ran
        System.out.println("Welcome to your music library!");


do {

            //Menu Prompts printed to the screen for the user to select from
            System.out.println(" ");
            System.out.println("Main Menu:");
            System.out.println("........ \n"); 
            System.out.println("Press 0 to Exit");
            System.out.println("Press 1 to Add a Song");
            System.out.println("Press 2 to View All Songs");
            System.out.println("Press 3 to Remove a Song");
            System.out.println("Press 4 to Shuffle Library");
            System.out.println("Press 5 to Play a Random song");
            System.out.println("Press 6 to Remove ALL Songs");
            System.out.println("Press 7 to Save Library\n");

            //Monitors the next Int the user types
            opt = input.nextInt();

            //"if" statements
            if (opt == 0) {
                //This corresponds to the condition of the while loop,      
                //The program will exit and print "Goodbye!" for the user.  
                System.out.println(" ");
                System.out.println("Goodbye!");
            } else if (opt == 1) {
                //This method allows the user to add a song to the library.
                //With the format being Title, Artist, Year.
                System.out.println(" ");
                menuFunctions.addEntry();
            } else if (opt == 2) {
                //This method prints the contents of the Array List to the screen  
                System.out.println("\n");
                menuFunctions.viewAll();
            } else if (opt == 3) {
                //This method allows the user to remove an indiviual song from
                //their music library  
                System.out.println("\n");
                menuFunctions.removeOne();
            } else if (opt == 4) {
                //This method uses the Collections.shuffle method
                //to re-arrange the track list
                //song to simulate a music player's shuffle effect.
                System.out.println("\n");
                menuFunctions.shuffleSongs();

            } else if (opt == 5) {
                //This method will clear all contents of the library.
                //It will ask the user to confirm their choice.
                System.out.println("\n");
                menuFunctions.randomSong();
            } else if (opt == 6) {
                //This method will clear all contents of the library.
                //It will ask the user to confirm their choice.
                System.out.println("\n");
                menuFunctions.clearLibrary();
            }   

            else if (opt == 7) {

                try {
                    menuFunctions.saveLibrary();
                } catch (FileNotFoundException x) {
                    System.out.println("File not found. " + x);
                }
            }

            else {
                //If the user selects an incorrect number, the console will 
                //tell the user to try again and the main menu will print again
                System.out.println("\n");
                System.out.println("Incorrect Entry, please try again");
            }


        } //do-while loop
        while (opt > 0);



}

    }

My SongClass class which holds the constructor and Get/Set methods

package MainClass;

public class SongClass {

        private int songMinutes;
        private int songSeconds;
        private String songTitle;
    private String songArtist;
    private String songAlbum;
    private int songYear;

public SongClass(int m, int ss, String t, String art, String al, int y){
        songMinutes = m;
                songSeconds = ss;
        songTitle = t;
        songArtist = art;
        songAlbum = al;
                songYear = y;
    }

//GET METHODS

    public int getMinutes() {
        return songMinutes;
    }

    public int getSeconds() {
        return songMinutes;
    }

    public String getTitle() {  //
        return songTitle;
    }
    public String getArtist() {
        return songArtist;
    }
    public String getAlbum() {
        return songAlbum;
    }
    public int getYear() {
        return songYear;
    }

//SET METHODS

    public void setMinutes(int m){
        songMinutes = m;
    }

     public void setDuration(int ss){
        songSeconds = ss;
    }

    public void setTitle(String t){
        songTitle = t;
    }   
    public void setArtist(String art){
        songArtist = art;
    }
    public void setAlbum(String al){
        songAlbum = al;
    }

    public void printSong(){
        System.out.println(songMinutes+":"+ songSeconds + " - " + songTitle + " - " + songArtist + " - " +songAlbum + " - "+ "("+songYear+")");
    } 

}

My menu class which holds most of the methods used in the program

package MainClass;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

public class Menu {

    public void add(SongClass s) throws NumberFormatException {
        try {
            songLibrary.add(s);
        } catch (NumberFormatException x) {
        }

    }
    Scanner input = new Scanner(System.in);
    UserInput ui = new UserInput();
    public ArrayList<SongClass> songLibrary;

    public Menu() {
        songLibrary = new ArrayList<SongClass>();
    }

    public void removeOne() throws ArrayIndexOutOfBoundsException {

        try {

        System.out.println("Which song would you like to delete? (1 of " + songLibrary.size() + ")");
        viewAll();
        //calls the viewAll method to print current library to screen

        int remove = input.nextInt();
        //creates an int that corresponds to the nextInt typed.

        if (remove > songLibrary.size()) {
            System.out.println("Invalid ");
            //if the user types a number higher than the highest index of the
            //array list, they will be shown an error and return to the menu

        }

        else { 
            remove --;
            SongClass s = songLibrary.get(remove);
            System.out.println("Are you sure you would like to delete the following track from your music library? "); 
            s.printSong();
             //confirms user wants to delete the selected track

            System.out.print("1: Yes \n2: No" + "\n");
            int confirmDelete = input.nextInt();
            //Asks the user to input 1 or 2, 

            if (confirmDelete == 1) {
                songLibrary.remove(remove);
                //removes the index of the 4 array lists
                System.out.println( "Removed.");
                viewAll();
            } else if (confirmDelete == 2) {
                System.out.println("\n" + "Okay, the song won't be removed");
            } else {
                System.out.println("\n" + "Invalid option.");
            }

        }
        }
        catch (ArrayIndexOutOfBoundsException x) {
            System.out.println("Please select an valid entry");
        }
    }

    public void clearLibrary() {
        System.out.println("Confirm?");
        System.out.print("1: Yes \n2: No" + "\n");

        int confirmDelete = input.nextInt();
        //if the user types one, this triggers the clear method.

        if (confirmDelete == 1) {
            songLibrary.clear();
            System.out.println("\n" + "Your music library has been cleared" + "/n");
        }

    }

    public void shuffleSongs() {
        //The shuffle function shifts the location of all the elements of an 
        //array list. This mimics the shuffle effect of a Music player
        //The attributes of the song all get shuffled together because they 
        //are all linked by the same seed.

        long seed = System.nanoTime();
        Collections.shuffle(songLibrary, new Random(seed));
        System.out.println("Your library is now shuffled" + "\n");
        viewAll();

        //Shuffles library, then outputs the new library list.
    }

    public void viewAll() {

        if (songLibrary.isEmpty()) {
            System.out.println("Your library is currently empty!");
        } else {

            System.out.println("Your Music Library" + "\n" + "Duration - Artist - Song - Album -(Year)  " + "\n");
            for (int i = 0; i < songLibrary.size(); i++) {
                SongClass s = songLibrary.get(i);
                s.printSong();
            }
        }


        System.out.println("\n");
    }

    public void randomSong() {

        int randomSong = (int) (Math.random() * (songLibrary.size() - 1));
        //uses Math.random to generate a random double between 0.0 and 1.0
        //it then multiplies it by the size of the array list - 1
        //The end result is that a random index of the array list is selected

        System.out.println("Now Playing:");
        //the selected song randomSong is then outputted
        //this changes each time the randomSong method is called
        SongClass s = songLibrary.get(randomSong);
        s.printSong();

    }



    public void saveLibrary() throws FileNotFoundException {

        try (PrintWriter pw1 = new PrintWriter("MUSIC LIBRARY.txt")) {
            File inFile = new File("MUSIC LIBRARY.txt");
            Scanner in = new Scanner(inFile);
            System.out.println("Your music library has been successfully exported!\n");
            pw1.println("Your Music Library");
            pw1.println(" ");
            pw1.println("Duration - Artist - Song - Album (Year)  " + "\n");
            pw1.println(" ");

            for (int i = 0; i < songLibrary.size(); i++) {
                System.out.println("The loop ran this many times");
                System.out.println(i);
                int counter = i + 1;
                pw1.println(counter + ": " + songLibrary.get(i));
            }
            System.out.println("Loop is over, PrintWriter should close.");
            pw1.close();
        }
    }



    public void addEntry() throws NumberFormatException {

        try {
            int minutes = ui.getInt("How many minutes does this song last?");
            int seconds = ui.getInt("How many seconds does this song last?");
            String title = ui.getString("What is the title of the track?");
            String artist = ui.getString("Who performs the track?");
            String album = ui.getString("What album is the track from?");
            int year = ui.getInt("What year was the track released?");
            System.out.println("Please enter a number:");
            System.out.println("\n");
            SongClass s = new SongClass(minutes, seconds, title, artist, album, year);
            songLibrary.add(s);
            System.out.println("Thank you!" + " " + title + " " + "was added to your library:");



        } catch (NumberFormatException x) {

            System.out.println(" ");
            System.out.println("Year/Duration can use numbers only, please try again.");
            System.out.println(" ");
        }

    }
}

And my user input class

package MainClass;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class UserInput{

    private Scanner keyboard;

    public UserInput() {
        this.keyboard = new Scanner(System.in);
    }

    public String getString(String prompt) {
        String line;

        System.out.print(prompt + ": ");
        line = this.keyboard.nextLine();

        return line;
    }

    public int getInt(String prompt) {
        String line;
        int num;

        System.out.print(prompt + ": ");
        line = this.keyboard.nextLine();
        num = Integer.parseInt(line);

        return num;
    }

    public Date getDate(String prompt) {
        String line;
        SimpleDateFormat formatter;
        Date date;

        System.out.print(prompt + " (dd/MM/yyyy): ");
        line = this.keyboard.nextLine();

        formatter = new SimpleDateFormat("dd/MM/yyyy");
        try {
            date = formatter.parse(line);
        }
        catch (ParseException ex) {
            date = null;
        }


        return date;
    }

    public boolean getBoolean(String prompt) {
        String line;

        System.out.print(prompt + "? (Y|N)");
        line = this.keyboard.nextLine();

        return line.equalsIgnoreCase("Y");
    }
}

Upvotes: 1

Views: 2066

Answers (1)

Thilo
Thilo

Reputation: 262464

"1: MainClass.SongClass@c137bc9 MainClass.SongClass@c137bc9"

This is what the default implementation of toString outputs.

You need to override toString in your SongClass:

@Override
public String toString(){
   return String.format("%d:%d - %s - %s - %s - (%d)", 
      songMinutes,songSeconds, songTitle, songArtist , songAlbum, songYear);
}

An alternative (which may be better if you don't want to override toString, because that method is used elsewhere) is to loop over all elements of your list and explicitly format the output by calling appropriate getters (or another method similar to your printSong method).

Upvotes: 2

Related Questions