gpt4 book ai didi

java - 如何将数组列表的内容写入文本文件?

转载 作者:行者123 更新时间:2023-11-30 04:32:02 24 4
gpt4 key购买 nike

我有一个足够基本的 Java 程序,它要求用户将歌曲输入到音乐库数组列表中。从那里,用户可以随机播放歌曲、删除一首歌曲、删除所有歌曲等。它即将完成,我只是有一个无法解决的问题。当我尝试将数组列表导出到文本文件时会发生这种情况。我的输出将如下所示,而不是数组列表的内容,而不是用户提交的详细信息:

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

我将在下面发布我的代码,如果有人能指出我正确的方向,我将非常感激!

我的最终项目类(class)作为我的主类(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);



}

}

我的 SongClass 类包含构造函数和 Get/Set 方法

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+")");
}

}

我的菜单类包含程序中使用的大部分方法

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(" ");
}

}
}

还有我的用户输入类

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");
}
}

最佳答案

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

这是 toString 的默认实现输出的内容。

您需要在 SongClass 中重写 toString:

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

另一种方法(如果您不想重写 toString ,这可能会更好,因为该方法在其他地方使用)是循环遍历列表的所有元素,并通过调用适当的 getter(或类似的其他方法)显式格式化输出到您的 printSong 方法)。

关于java - 如何将数组列表的内容写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14410131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com