我的程序只在打印文本文件时打印出一堆“空”

时间:2015-10-14 07:07:10

标签: java arrays file-io

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

此程序用于将歌曲和艺术家列表显示为CD。歌曲类是我的打印格式,compactDisc类读取包含歌曲和艺术家列表的文件到一个数组,主程序打印它们。但是,当我运行程序时,它打印出null nullnull nullnull nullnull nullnull nullnull null而不是实际列表,方向似乎正确。我想知道为什么会这样。

3 个答案:

答案 0 :(得分:3)

在Song课程中查看此内容。

private String title;
private String artist;

public Song (String Title, String Artist) {
   Title = title;
   Artist = artist;
}

您要将未从Song类初始化的空值分配到参数中,因此您的classvariables将永远不会被填充。

它应该看起来像这样

public class Song {
   private String title;
   private String artist;

   public Song (String title, String artist)  {
      this.title = title;
      this.artist = artist;
   }
}

同样,通过约定,类应以大写字母开头,变量应以小写字母开头。

答案 1 :(得分:0)

问题出在这里

public Song (String Title, String Artist)
{
    Title = title;
    Artist = artist;
}

参数是标题,但您要分配标题(为空);

更改为:

title = Title;
artist = Artist;

答案 2 :(得分:0)

问题出在Song课程中,如(我)的评论中所述:

public Song (String Title, String Artist)
{
    Title = title;   // assigns this.title into local Title
    Artist = artist; // assigns this.artist into local Artist
}