//filename:ArrayDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class ArrayDemo extends JFrame implements ActionListener
{
TextField t1 = new TextField(40);
TextField t2 = new TextField(40);
TextField t3 = new TextField(10);
JLabel label = new JLabel("sum:");
JButton button1 = new JButton("数组排列");
JButton button2 = new JButton("数据求和");
int array[];
//
public ArrayDemo()
{
Container container = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.LEFT));
container.add(t1);
container.add(t2);
container.add(button1);
container.add(button2);
container.add(label);
container.add(t3);
button1.addActionListener(this);
button2.addActionListener(this);
}
//
public static void main(String[] args)
{
ArrayDemo frame = new ArrayDemo();
frame.setTitle("数组排序&求和");
frame.setSize(400,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//
public void actionPerformed(ActionEvent e)
{
StringTokenizer fenxi = new StringTokenizer(t1.getText(),",");
int n = fenxi.countTokens();
array = new int[n];
int j = 0;
while(fenxi.hasMoreTokens())
{
array[j] = Integer.parseInt(fenxi.nextToken());
System.out.println(array[j]);
j++;
}
if(e.getSource()==button1)
{
sort();
t2.setText("");
for(int i=0;i<array.length;i++)
if(i==0)
t2.setText(""+array[i]);
else
t2.setText(t2.getText()+","+array[i]);
}
if(e.getSource()==button2)
{
getSum();
t3.setText(String.valueOf(getSum()));
}
}
//
long getSum()
{
long result = 0;
for(int i=0;i<array.length;i++)
result = result+array[i];
return result;
}
//
void sort()
{
int temp;
for(int i=0;i<array.length-1;i++)
{
for(int j=i+1;j<array.length;j++)
{
if(array[i]>array[j])
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
}
}