Java程序仅打印数组最后一段内容的问题求助
问题:读取文件生成二维数组后重复输出最后一条内容
问题背景
教授要求补全指定代码,通过Classics.txt文件创建二维数组并输出内容,但运行程序后,仅重复显示数组最后一段内容。要求不得修改教授提供的代码,仅能补全标注// CODE I INPUT MYSELF区域的代码。
完整代码
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 = null; String artist = null; // CODE I INPUT MYSELF int column = 0; String cd[][] = new String[6][6]; // END for (int i = 0; i < cd.length; i++) { // CODE I INPUT MYSELF title = input.readLine(); artist = input.readLine(); cd[i][column] = title; column++; cd[i][column] = artist; column = 0; // END } System.out.println("Contents of Classics:"); for (int i = 0; i < cd.length; i++) { // CODE I INPUT MYSELF Song track = new Song(title, artist); System.out.print(track); // END } } } class Song extends CompactDisc{ private String title; // The song's title private String artist; // The song's artist /** Constructor @param title A reference to a String object containing the song's title. @param artist A reference to a String object containing the song's artist. */ public Song(String title, String artist) { this.title = title; this.artist = artist; } /** The toString method @return A String object containing the name of the song and the artist. */ public String toString() { return title + " by " + artist + "\n"; } }
Classics.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: The Blue Danube Waltz by Strauss The Blue Danube Waltz by Strauss The Blue Danube Waltz by Strauss The Blue Danube Waltz by Strauss The Blue Danube Waltz by Strauss The Blue Danube Waltz by Strauss
问题根源
最后一个循环中,直接使用了全局变量title和artist——这两个变量在第一个循环结束后,已经被赋值为文件最后一行的内容,所以每次创建Song对象时都用的是这组最后值,导致重复输出。此外,虽然把数据存入了二维数组cd,但输出阶段完全没有用到这个数组。
修正方案
仅修改标注区域的代码即可解决问题:
1. 第一个补全区(数组定义)
可以优化数组大小(非必须,但更合理),因为每组仅需存储标题和艺术家两个元素:
// CODE I INPUT MYSELF String cd[][] = new String[6][2]; // 6组数据,每组2个元素 // END
(原代码的6x6数组也能运行,只是浪费空间,可根据需求选择)
2. 第二个补全区(数据存入数组)
可以简化赋值逻辑,去掉冗余的column变量:
// CODE I INPUT MYSELF title = input.readLine(); artist = input.readLine(); cd[i][0] = title; // 第0列存标题 cd[i][1] = artist; // 第1列存艺术家 // END
3. 第三个补全区(读取数组并输出)
这是核心修正点,必须从二维数组中读取对应索引的元素,而非复用全局变量:
// CODE I INPUT MYSELF Song track = new Song(cd[i][0], cd[i][1]); System.out.print(track); // END
修正后输出
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
内容的提问来源于stack exchange,提问作者PatPatis
相关产品推荐
相关产品推荐

