参考代码如下:
import java.util.*
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in)
int sum = 0
int count = 0
while(true){
int num = sc.nextInt()
if(num == 0) break
sum += num
count++
}
System.out.println("平均值:"+sum*1.0/count)
}
}
运行结果:
参考下面代码:import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JLabel
public class Test extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L
private JLabel lbl
private JButton btn1
private JButton btn2
private JButton btn3
private int con
public static void main(String args[]) {
try {
Test test = new Test()
test.setVisible(true)
} catch (Exception e) {
e.printStackTrace()
}
}
public Test() {
super()
getContentPane().setLayout(null)
setTitle("Test")
setName("")
setResizable(false)
setBounds(100, 100, 300, 216)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
lbl = new JLabel()
lbl.setText(String.valueOf(con))
lbl.setBounds(84, 58, 96, 25)
getContentPane().add(lbl)
btn1 = new JButton()
btn1.setText("+ 1")
btn1.setBounds(29, 106, 64, 26)
btn1.addActionListener(this)
getContentPane().add(btn1)
btn2 = new JButton()
btn2.setText("- 1")
btn2.setBounds(99, 106, 64, 26)
btn2.addActionListener(this)
getContentPane().add(btn2)
btn3 = new JButton()
btn3.setText("Clear")
btn3.setBounds(169, 106, 64, 26)
btn3.addActionListener(this)
getContentPane().add(btn3)
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn1) {
con = Integer.parseInt(lbl.getText())
con++
lbl.setText(String.valueOf(con))
}
if (e.getSource() == btn2) {
con = Integer.parseInt(lbl.getText())
con--
lbl.setText(String.valueOf(con))
}
if (e.getSource() == btn3) {
lbl.setText(String.valueOf(0))
}
}
}