【问题标题】:Java homework: using an equals method with an array of objects [closed]Java作业:使用带有对象数组的equals方法[关闭]
【发布时间】:2012-09-26 01:45:33
【问题描述】:

我创建了一组 Song 对象。一首歌包含变量标题、作者、解释器、(int)yearReleased、专辑和文件名。我正在使用 main 方法来测试我的歌曲数组和 equals 方法。该测试应该用五个歌曲对象填充一个数组,并使用我的 equals 方法来确保新条目不是先前条目的重复。我的测试类可以编译,但是当我输入重复的歌曲信息时,我不断收到错误消息。如果有人能给我提示或指出正确的方向,我将不胜感激。任何其他提示也会很棒。作为一名学生,很高兴听到专业人士在现实世界中提出的良好建议。

 import java.util.Scanner;

 public class Test{
 public static void main(String[] args)
 {
    Scanner kybd = new Scanner(System.in);

    Song[] songTest = new Song[5];
    boolean match;
    int count = 0;

    System.out.println("Enter 5 songs\n");

    for(Song x:songTest)
    {
        do{
            match = false;
            x = new Song();
            System.out.print("Title: ");
            x.setTitle(kybd.nextLine());
            System.out.print("Author: ");
            x.setAuthor(kybd.nextLine());
            System.out.print("Interpreter: ");
            x.setInterpreter(kybd.nextLine());
            System.out.print("Year released: ");
            x.setYearReleased(kybd.nextInt());
            kybd.nextLine();
            System.out.print("Album: ");
            x.setAlbum(kybd.nextLine());
            System.out.print("File name: ");
            x.setFileName(kybd.nextLine());
            System.out.print(x);
            System.out.println();
            for(int i = 0; i<count; i++)
                if(songTest[i].equals(x)){
                    match = true;
                    System.out.print("Duplicate");
                }
        }while(match);
        count++;
    }
}
}




public class Song
{
public String title;
public String author;
public String interpreter;
public int yearReleased;
public String album;
public String fileName;

//private vars
private int reviewScore = 0;
private int reviews = 0;
private double average;

//Mutator methods

public void setTitle(String t)
{
    this.title = t;
}

public void setAuthor(String a)
{
    this.author = a;
}

public void setInterpreter(String i)
{
    this.interpreter = i;
}

public void setYearReleased(int y)
{
    if (y>0)
        this.yearReleased = y;
    else
    {
        System.out.print ("This song is not that old");
        this.yearReleased = -5;
    }
}

public void setAlbum(String a)
{
    this.album = a;
}

public void setFileName(String f)
{
    this.fileName = f;
}

public void addReviewScore(int s)
{
    if (s>0 && s<6)
    {
        this.reviewScore += s;
        this.reviews++;
    }
    else
        System.out.print("This is not a valid review score!");
}

//Accessor methods

public String getTitle()
{
    return this.title;
}

public String getAuthor()
{
    return this.author;
}

public String getInterpreter()
{
    return this.interpreter;
}

public int getYearReleased()
{
    return this.yearReleased;
}

public String getAlbum()
{
    return this.album;
}

public String getFileName()
{
    return this.fileName;
}

public double getAverage()
{
    this.average = this.calculateAverage();
    return this.average;
}

//Methods

public boolean equals(Song otherSong)
{
    boolean isEqual = false;
    //compare this song to the otherSong
    isEqual =
        this.title == otherSong.title &&
        this.author == otherSong.author &&
        this.interpreter == otherSong.interpreter &&
        this.yearReleased == otherSong.yearReleased &&
        this.album == otherSong.album &&
        this.fileName == otherSong.fileName;
    return isEqual;
}
public String toString()
{
    String songInfo;
    songInfo = 
        "***Song information***\n" +
        "Title: " + this.title + 
        "\nAuthor: " + this.author +
        "\nInterpreter: " + this.interpreter +
        "\nYear Released: " + this.yearReleased +
        "\nAlbum: " + this.album +
        "\nFile name: " + this.fileName +
        "\nYears old: " + this.yearsOld(); 
    return songInfo;
}

public int yearsOld()
{
    int yearsOld = (2012 - this.yearReleased);
    return yearsOld;
}

//Private methods
private double calculateAverage()
{
    this.average = ((double)this.reviewScore/(double)this.reviews);
    return this.average;

}

}

【问题讨论】:

  • “我不断收到错误”。当某些事情没有按照您的预期工作时,请始终完整描述您的预期和实际结果,和/或在“发生错误”时提供堆栈跟踪。
  • 对于String 比较,您应该始终使用equals() 方法来比较两个字符串的值,而不是==== 比较两个字符串对象是否指向相同的内存位置。 equals() 进行实际值比较。
  • 您确定您知道比较字符串的正确方法是什么吗?你的 equals 方法对我来说似乎有问题。在 Google 或 StackOverflow 中简单搜索一下“Java 字符串比较”
  • 仅供参考,如果您使用 netbeans IDE,它会自动为您生成 equals 方法的原型。但这个练习的重点是学习如何去做。
  • 如果您覆盖 equals(),请确保您遵循 hashcode contract

标签: java arrays object equals


【解决方案1】:

我尝试了您的代码并重现了此行发生的错误:

                if(songTest[i].equals(x)){

重写你的 equals 方法(或让 eclipse 为我做)并添加 hashCode() 解决了问题:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((album == null) ? 0 : album.hashCode());
    result = prime * result + ((author == null) ? 0 : author.hashCode());
    long temp;
    temp = Double.doubleToLongBits(average);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    result = prime * result
            + ((fileName == null) ? 0 : fileName.hashCode());
    result = prime * result
            + ((interpreter == null) ? 0 : interpreter.hashCode());
    result = prime * result + reviewScore;
    result = prime * result + reviews;
    result = prime * result + ((title == null) ? 0 : title.hashCode());
    result = prime * result + yearReleased;
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Song other = (Song) obj;
    if (album == null) {
        if (other.album != null)
            return false;
    } else if (!album.equals(other.album))
        return false;
    if (author == null) {
        if (other.author != null)
            return false;
    } else if (!author.equals(other.author))
        return false;
    if (Double.doubleToLongBits(average) != Double
            .doubleToLongBits(other.average))
        return false;
    if (fileName == null) {
        if (other.fileName != null)
            return false;
    } else if (!fileName.equals(other.fileName))
        return false;
    if (interpreter == null) {
        if (other.interpreter != null)
            return false;
    } else if (!interpreter.equals(other.interpreter))
        return false;
    if (reviewScore != other.reviewScore)
        return false;
    if (reviews != other.reviews)
        return false;
    if (title == null) {
        if (other.title != null)
            return false;
    } else if (!title.equals(other.title))
        return false;
    if (yearReleased != other.yearReleased)
        return false;
    return true;
}

您似乎也遇到了计数器未正确递增的问题,但我不会为您做所有的功课! ;)

编辑: 哇! 您还缺少类似

的内容
       songTest[i] = song;

将选中的歌曲添加到您的数组中。

另外,为了确保您的第一首歌曲被放入,我添加了:

if(i==0){
        songTest[i] = x;
}

在您检查之前。 我通过将您的第一个 for 循环更改回旧版本来添加 i is 和 int,并将您的内部 for 循环重命名为 j。 现在它起作用了。 尝试放入类似的东西:

System.out.println("i: " + i + " j: " + j + " count: " + count);

查看您的计数器发生了什么

您也可以在找到重复项后退出。这是你想要的行为吗?还是通知用户,继续输入歌曲数据比较好。

【讨论】:

【解决方案2】:

当我运行这个时,我在这一行得到一个空指针异常

if(songTest[i].equals(x)){

看起来您实际上并未将歌曲对象 (x) 放入数组中。

【讨论】:

  • 我同意。看来您正在循环一个空数组。也许增强的 for 循环不是遍历数组的最佳选择。而是在循环中执行 for(int i=0;i
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 2020-02-12
相关资源
最近更新 更多