我是java的新手,我正在尝试创建一个程序来测试用户对2个随机频率之间的差异。一切都有效,除了当我试图获得2个频率的差异时,答案总是为0.我如何才能显示实际差异?这是我写的用来创建音调的类来计算差异:
public class Quiz{
private PitchPlay one = new PitchPlay();
private PitchPlay two = new PitchPlay();
private int frequencyOne;
private int frequencyTwo;
private int dif = new Integer(Math.abs(frequencyTwo - frequencyOne));
public int run(){
frequencyOne = new Integer((int)(Math.random() * 5000 + 50));
frequencyTwo = new Integer((int)(Math.random() * 5000 + 50));
return this.dif;
}
public int freqDif(){
return this.dif;
}
public void playQuiz(){
one.play(one.note(frequencyOne, 2, 15));//note(frequency, duration, volume)
two.play(two.note(frequencyTwo, 2, 15));
}
}
以下是使用测验类的课程:
public class Action implements ActionListener{
Quiz one = new Quiz();
public void actionPerformed (ActionEvent e){
if(e.getSource() == playSoundButton)
{
if(answerResponse.getText().compareTo("Correct!") == 0 || answerResponse.getText().compareTo("Play and Listen...") == 0)
{
one.run();
one.playQuiz();
}
else
{
one.playQuiz();
}
}
if(e.getSource() == submitButton)
{
String responseText = new String(responseField.getText());
if(responseText !=null && !"".equals(responseText)){
try{
Integer responseNumber = Integer.parseInt(responseText);
if(responseNumber == one.freqDif())
{
answerResponse.setText("Correct!");
answerResponse.setVisible(true);
}
else
{
answerResponse.setText("Wrong Answer. The difference is " + one.freqDif() + " hertz.");
answerResponse.setVisible(true);
}
}catch(NumberFormatException f){
f.printStackTrace(System.out);
}
}
}
}
}
答案 0 :(得分:2)
private int dif = new Integer(Math.abs(frequencyTwo - frequencyOne));
这是在创建变量时计算的,而不是在使用变量时计算的。您需要在分配变量后进行计算。
答案 1 :(得分:0)
您的代码存在以下问题:
正如其他人所说,行
private int dif = new Integer(Math.abs(frequencyTwo - frequencyOne));
创建一个变量并指定一个从其他两个变量计算出来的值。使用创建时其他变量的值。每次这两个变量的值发生变化时,都需要重新计算。这不会自动发生。
new Integer(...)
创建一个Integer
对象。随后将此对象分配给int
变量时,将从对象中取出该值。这会为您的代码增加一些不必要的内存和运行时间。相反,您应该直接分配给您的变量。例如,
frequencyOne = (int)(Math.random() * 5000 + 50);