java ----- 数组累加计算器 求平均值

MyJFrame.java

import java.awt.Button;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.text.DecimalFormat;
import java.util.StringTokenizer;

import javax.swing.JFrame;

public class MyJFrame extends JFrame implements TextListener, ActionListener
{
	TextArea text1;
	TextArea text2;
	Button button;
	//MyImageJPanel image;
	
	public MyJFrame()
	{
		setExtendedState(Frame.MAXIMIZED_VERT);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(450, 150, 100, 200);
		setSize(500, 500);	
		this.setTitle("计算的窗口");
		//setLocationRelativeTo(this);
		Container con = getContentPane();
		con.setLayout(new FlowLayout());
		//image = new MyImageJPanel();
		//image.setBounds(0, 0, this.getWidth(), this.getHeight());
		text1 = new TextArea();
		text2 = new TextArea();
		button = new Button("清空");
		button.setBackground(Color.lightGray);
		//con.add(image);
		con.add(text1);
		con.add(text2);
		con.add(button);
		text2.setEditable(false);
		text1.addTextListener(this);
		button.addActionListener(this);
		setVisible(true);
		validate();
	}

	public void textValueChanged(TextEvent e) {
		String s = text1.getText();
		StringTokenizer st = new StringTokenizer(s, " ,'\n'");
		int n = st.countTokens();
		String a[] = new String[n];
		
		for(int i = 0; i <= n - 1; i++)
		{
			String temp = st.nextToken();
			a[i] = temp;
		}
		
		double addResult = 0;
		double aveResult = 0;
		for(int i = 0; i < n; i++)
		{
			addResult +=  Double.valueOf(a[i]);
		}
		
		if(n != 0)
		{
			aveResult = addResult / n;
		}
		
		text2.setText(null);
		text2.append(n + "个数相加的和:	" + addResult + "\n");
		DecimalFormat d = new DecimalFormat("#.00"); 
		text2.append("平均值:	" + d.format(aveResult) + "\n");
		
	}
	
	public void actionPerformed(ActionEvent e) {
		text1.setText(null);
	}


}

TestJFrame.java

public class TestJFrame {
	public static void main(String[] args) {
		MyJFrame jFrame=new MyJFrame();
	}

}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值