字符串数组转换成整数型数组
import java.io.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import java.util.*;
/*<applet code = MyFrame.class width = 600 height = 200></applet>*/
public class MyFrame extends Applet implements ActionListener
{
Button b1 = new Button("排序");
Button b2 = new Button("插入");
Label lab1 = new Label("请输入数据:");
Label lab2 = new Label("排序前的数据:");
Label lab3 = new Label("排序后的数据:");
TextField f1 = new TextField(20);
public void init()
{
setLayout(null);
add(lab1);
lab1.setBounds(10, 10, 100, 20);
add(f1);
f1.setBounds(120, 10, 300, 20);
add(b1);
b1.setBounds(10, 40, 80, 30);
add(b2);
b2.setBounds(100, 40, 80, 30);
add(lab2);
lab2.setBounds(10, 80, 500, 20);
add(lab3);
lab3.setBounds(10, 120, 500, 20);
b1.addActionListener(this);
b2.addActionListener(this);
}
public String sort()
{
String a;
StringBuffer sa = new StringBuffer();
boolean flag = false;
a = f1.getText();
String s[] = a.split("\\t");/*分割字符串后,将字符串数组转换成整型。方便后面的排序*/
int s3[] = new int[s.length];
for(int i =0 ;i<s.length;i++)
s3[i] = Integer.parseInt(s[i]);/*将字符串数组转换成整型,结果出现异常。后面事件处理时,调用sort,出现错误。*/
for (int i = 1; i < s3.length; i++)
{ for (int j = 0; j < s3.length - i; j++)
{
if (s3[j] > s3[j + 1])
{
int t=0 ;
t = s3[j];
s3[j] = s3[j + 1];
s3[j + 1] = t;
flag = true;
}
else continue;
}
if (!flag) break;
}
for (int i = 0; i < s3.length; i++)
sa.append(s3[i] + " ");
return sa.toString();
}
public String PrintNum()
{ String b;
StringBuffer sb = new StringBuffer();
b = f1.getText();
String s1[] = b.split("\\t");
for (int i = 0; i < s1.length; i++)
sb.append(s1[i] + " ");
return sb.toString();
}
public void actionPerformed(ActionEvent e)
{ if (e.getSource() == b1)
{ lab2.setText("排序前的数据:" + PrintNum());
lab3.setText("排序后的数据:" + sort());
/*不显示数据。抛出异常,Exception in thread "AWT-EventQueue-1"
java.lang.NumberFormatException: For input string: "23 34 2 3 4 54"
at java.lang.
NumberFormatException.forInputString(NumberFormatException.java:48)*/
}
/* if (e.getSource() == b2)
{ lab1.setText("请输入要插入的数");