51,397
社区成员




import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Date;
/**
* Created by admin on 2016/5/8.
* 创建一个按钮,触发时获取当前时间
* 计算几次时间间隔的平均数,转换输出为bpm值
*/
public class Bpm extends Frame implements ActionListener {
private JButton beat;
private TextField bpm;
public Bpm() {
super("BPM计算");
this.setSize(200, 200);
this.setLocation(300, 240);
this.setBackground(Color.lightGray);
this.setLayout(new FlowLayout());
bpm = new TextField("0", 4);
this.add(bpm);
beat = new JButton("咚!");
this.add(beat);
beat.addActionListener(this);
this.addWindowListener(new WinClose());
this.setVisible(true);
}
public static void main(String args[]) {
new Bpm();
}
class WinClose implements WindowListener {
public void windowClosing(WindowEvent ev) {
System.exit(0);
}
public void windowOpened(WindowEvent ev) {
}
public void windowActivated(WindowEvent ev) {
}
public void windowDeactivated(WindowEvent ev) {
}
public void windowClosed(WindowEvent ev) {
}
public void windowIconified(WindowEvent ev) {
}
public void windowDeiconified(WindowEvent ev) {
}
}
public void actionPerformed(ActionEvent ev) {
Date[] date = new Date[180];
int i = 0;
long sum = 0;
if (ev.getSource() == beat) {
date[i] = new Date();
i++;
for (int j = 1; j < i; j++) {
long time = date[j].getTime() - date[j - 1].getTime();
sum = sum + time;
}
bpm.setText(String.valueOf(sum / i));//为什么这里无法使用j?
}
}
}
public void actionPerformed(ActionEvent ev) {
Date[] date = new Date[180];
int i = 0;
long sum = 0;
if (ev.getSource() == beat) {
date[i] = new Date();
i++;
for (int j = 1; j < i; j++) {
long time = date[j].getTime() - date[j - 1].getTime();
sum = sum + time;
}
bpm.setText(String.valueOf(sum / i));// 为什么这里无法使用j?
}
}
每次点击按钮后,到第8行时:i=1,而j初始化为1,这个循环就直接退出了;因此sum取值0,sum / i取值自然是0。
不晓得你想实现的逻辑是什么样的。
至于为什么不能用j?因为不在它的作用域里。