gpt4 book ai didi

java - 以适当的顺序将项目添加到数组中

转载 作者:行者123 更新时间:2023-11-30 03:59:35 25 4
gpt4 key购买 nike

我无法弄清楚如何正确执行此操作。所以我有这个可以包含 6 个项目的数组。我有一个 .txt 文件,其中一行包含一首歌曲,然后是该歌曲的作者,然后是下一首歌曲,然后是该歌曲的作者。对于一些人来说,依此类推。我的 .txt 文件总共有 12 行,但我只能在数组中放入总共 6 个项目。所以我想知道,如何将歌曲标题+艺术家放入数组的单个索引中。这样我以后就可以将其打印出来,作为“艺术家”的标题。

我的代码相当短,所以查看它可能会有所帮助。

/**This program creates a list of songs for a CD by reading from a file*/
import java.io.*;

public class CompactDisc
{
public static void main(String [] args) throws IOException
{
FileReader file = new FileReader("Classics.txt");
BufferedReader input = new BufferedReader(file);
String title;
String artist;

//Declare an array of songs, called cd, of size 6
String[] cd = new String[6];

for (int i = 0; i < cd.length; i++)
{
title = input.readLine();
artist = input.readLine();
// fill the array by creating a new song with
// the title and artist and storing it in the
// appropriate position in the array
cd.add(title + artist);
}

System.out.println("Contents of Classics:");
for (int i = 0; i < cd.length; i++)
{
//print the contents of the array to the console
}
}
}

这是 .txt 文件中的内容

Ode to Joy
Bach
The Sleeping Beauty
Tchaikovsky
Lullaby
Brahms
Canon
Bach
Symphony No. 5
Beethoven
The Blue Danube Waltz
Strauss

最终输出应该打印为:

Contents of Classics
Ode to Joy by Bach
The Sleeping Beauty by Tchaikovsky
Lullaby by Brahms
Canon by Bach
Symphony No. 5 by Beethoven
The Blue Danube Waltz by Strauss

最佳答案

您只需替换:

cd.add(title + artist);

作者:

cd[i] = title + " by " + artist;

然后打印它:

System.out.println(cd[i]);

关于java - 以适当的顺序将项目添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22290248/

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