由于我自己研究了编程,我认为我应该开始创建适当的类和变量,但我似乎没有得到它。
我已经读过,首先我需要一个interface
,所以我让我看起来像这样:
public interface PitchInterface {
void setOccuranceTime(float occuranceTime);
float getOccuranceTime();
void setPitch(float pitch);
float getPitch();
}
其次,我创建了一个实现interface
:
public class Pitch implements PitchInterface{
float occuranceTime;
float pitch;
@Override
public void setOccuranceTime(float occuranceTime) {
this.occuranceTime = occuranceTime;
}
@Override
public float getOccuranceTime() {
return occuranceTime;
}
@Override
public void setPitch(float pitch) {
this.pitch = pitch;
}
@Override
public float getPitch() {
return pitch;
}
}
现在我需要为Pitch
提供值,这就是我现在被困住的地方:
public class Foo {
Pitch pitch = new Pitch();
String[] pitches;
List<Pitch> listOfPitches = new ArrayList<Pitch>();
List<String> wordsList = new ArrayList<String>();
public List<Pitch> getListOfPitches(){
getPitches();
for (String pitchString: pitches) {
makeListOfPitches(pitch, pitchString);
}
return listOfPitches;
}
public void makeListOfPitches(Pitch pitch, String pitchString){
pitch.setPitch(getPitchesInfo(pitchString, 0));
pitch.setOccuranceTime(getPitchesInfo(pitchString, 1));
listOfPitches.add(pitch);
}
public List<String> getWordsList(){
//To-do make words out of Pitches and add them to list
return wordsList;
}
public String[] getPitches() {
pitches = pitchesRaw.split("\\r?\\n");
return pitches;
}
private float getPitchesInfo(String pitch, int position){
String[] frequencyAndTime = pitch.split("\\:");
if(position == 0){
return Float.parseFloat(frequencyAndTime[0].replace(',', '.'));
}
if(position == 1){
return Float.parseFloat(frequencyAndTime[1].replace(',', '.'));
}
else return 0;
}
String pitchesRaw = "0,14:23281,61\n" +
"0,23:53,65\n" +
"0,37:72,53\n" +
"0,56:86,09\n" +
"0,60:88,58\n" +
"0,65:87,45\n" +
"0,70:87,11\n" +
"0,74:89,56\n" +
"0,79:96,22\n" +
"0,84:23288,24\n" +
"0,88:103,92\n" +
"0,93:107,46\n" +
"0,98:108,02\n" +
"1,02:107,51\n" +
"1,07:104,92\n" +
"1,11:105,94\n" +
"1,16:106,40\n";
}
最后从Main类初始化它:
public static void main(String[] args) {
Foo listOfWordsAndPithes = new Foo();
List<Pitch> list = listOfWordsAndPithes.getListOfPitches();
for (Pitch pitch: list) {
System.out.println(pitch.getPitch());
}
}
首先,如果我在循环中打印出所有pitches
,如上所示,我将下面显示的值作为输出。但我想要的是每个音高具有与pitchesRaw
106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4 106.4
其次,如果我需要通过将多个words list
添加到一个列表中(例如将6个不同的Pitch添加到1个列表中)而使Pitches
超出节距,然后添加{{1}另一个列表,它将是新列表的第一个元素。那么我是否需要制作另一个名为Pitches
的{{1}},并在那里定义哪个词以及如何设置/获取它?
第三,我从评论中读到,不需要使用Interface。我何时才知道使用界面是否可以?何时没有?
答案 0 :(得分:1)
要回答问题的最后部分,在这里使用接口既不好也不坏,您实际上是为您的getter和setter创建一个接口,是否必要取决于您希望如何使用该接口。在您的情况下,它看起来没有必要。看看Java Interface Usage Guidelines -- Are getters and setters in an interface bad?
关于你的第二个问题,你可能也不需要一个单独的类来实例化音高列表,word
实际上有意义并且会在别处被实例化为对象吗?如果您只想要一个列表,只需执行上面List<Pitch> word = new ArrayList<Pitch>();
所做的操作,只需将间距添加到列表中即可。