gpt4 book ai didi

java - 我需要帮助才能正确实现 Comparable 接口(interface)

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:22 24 4
gpt4 key购买 nike

我构建了一个名为 Melody 的类,它从文件中读取以下几行并将它们存储到名为 Note 类型的音符的数组中。这些列是:以 1/100 秒为单位的时间、音符编号、速度、长度。

0 60 100 24
25 72 100 24
100 60 100 24
50 60 100 24
75 72 100 24

对于我的类(class)作业,我需要实现 Comparable 接口(interface)。我需要使我的 Note 类可比较,以便笔记根据时间排序,如果两个笔记同时出现,那么我需要将笔记编号较小的笔记放在前面。我需要一些帮助,因为我在尝试正确实现 comparaTo 方法并打印结果时遇到了困难。我将不胜感激任何帮助,提前致谢。

这是我的 Note 类

public class Note implements Comparable <Note> {  

private int time;
private int noteNumber;
private int velocity;
private int length;

public Note (int time,int noteNumber,int velocity,int lenght){

this.time = time;
this.noteNumber = noteNumber;
this.velocity = velocity;
this.length = lenght;
}

public String toString()
{

String s = time +" "+ noteNumber + " " + velocity + " " + length;

return s;
}

@Override
public int compareTo(Note o) {

return Integer.compare(time, o.time);
}
}

这是我的旋律课

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class Melody {

Note [] notes = new Note[5];

public Melody() throws IOException{

FileReader fr = new FileReader ("/Users/enricomomo/Desktop/Text/file2.txt");
BufferedReader br = new BufferedReader (fr); //Info stored into a buffer

String line = br.readLine(); //Lines are read from the buffer and stored into a variable

int lineCounter = 0;

while ( line != null )//When reached the end of the file the while loop stops

{

StringTokenizer st = new StringTokenizer(line, " ");

int time = Integer.parseInt(st.nextToken());
int noteNumber = Integer.parseInt(st.nextToken());
int velocity = Integer.parseInt(st.nextToken());
int length = Integer.parseInt(st.nextToken());

System.out.println(line + " " + lineCounter);

Note n = new Note(time,noteNumber,velocity,length);

notes[lineCounter] = n;

line = br.readLine();

lineCounter ++;
}

br.close();
}

public void contet(){

for ( int i = 0; i < notes.length; i ++)
{

System.out.println(notes[i]);
}
}

public String toString()
{
String rtn = "";

//Code to create a String version of the object

for ( int i = 0; i < notes.length; i ++)
{

rtn += "\n";
}

return rtn;
}
}

这是我的测试课

import java.io.IOException;

public class Test {

public static void main(String[] args) throws IOException {

Melody m = new Melody();

System.out.print(m);

m.contet();
}
}

最佳答案

由于 timenoteNumberint:

@Override
public int compareTo(Note o) {
if (time == o.time)
return Integer.compare(noteNumber, o.noteNumber);
else
return Integer.compare(time, o.time);
}

compareTo 需要返回负数、零或正数,
取决于第一项是小于、等于还是大于第二项。
填充 Note 对象数组后,调用:

Arrays.sort(notes);

关于java - 我需要帮助才能正确实现 Comparable 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53818954/

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