目录
1 实验名称
String类
2 实验目的
掌握在eclipse中调试代码
掌握String类中方法的使用
掌握正则表达式的使用
3 实验源代码
package Text01.JsText;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyJFrame03 extends JFrame implements ActionListener{
private JButton jButton = null;
private JTextArea[] jTextAreas = null;
public MyJFrame03() {
}
public void init(){
this.setLayout(new FlowLayout());
jButton = new JButton("统计");
jTextAreas = new JTextArea[2];
jTextAreas[0] = new JTextArea(10,20);
jTextAreas[1] = new JTextArea(10,20);
/*jTextAreas[0].setLineWrap(true);//激活自动换行功能
jTextAreas[0].setWrapStyleWord(true);//激活断行不断字功能*/
JScrollPane jScrollPane = new JScrollPane(jTextAreas[0]);//二级容器,滚动窗格
this.add(jScrollPane);
jTextAreas[1].setLineWrap(true);//激活自动换行功能
jTextAreas[1].setWrapStyleWord(true);//激活断行不断字功能
//貌似jScrollPane和jPanel不能嵌套使用,目前为止,分开可用
JPanel jPanel = new JPanel();
this.add(jPanel);
//jPanel.add(jTextAreas[0]);
jPanel.add(jButton);
jPanel.add(jTextAreas[1]);
//jButton.addActionListener(new MyActionListener());//按钮作为事件源触发事件
jButton.addActionListener(this);
this.setBounds(400,100,640,480);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//用窗口作为监听器
@Override
public void actionPerformed(ActionEvent e) {
int num0 = JOptionPane.showConfirmDialog(this,"是否继续");
if(num0 != 0){
return;
}
String strInput = jTextAreas[0].getText();
String regex = "[\\s ,。、,.;:!\\?-]";
String[] words = strInput.split(regex);
int num = words.length;
jTextAreas[1].setText(null);
jTextAreas[1].append("字的个数为:"+num+"\n");
for(int n=0;n<num;n++){
jTextAreas[1].append(words[n]+"\n");
}
}
//用按钮作为监听器触发事件
public class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String strInput = jTextAreas[0].getText();
String regex = "[\\s,。、,.;:!\\?-]";
String[] words = strInput.split(regex);
int num = words.length;
jTextAreas[1].setText(null);
jTextAreas[1].append("字词的个数为:"+num+"\n");
for(int n=0;n<num;n++){
jTextAreas[1].append(words[n]+"\n");
}
}
}
}
4 实验运行结果图
5 总结
此次实验步骤:首先定义字符串,在Java中,可以用双引号括起来的一组字符序列来定义字符串。在此次实验中,使用字符串字面值和构造函数两种方式定义字符串;其次操作字符串,Java中提供了各种字符串操作方法,比如字符串连接、截取、替换、转换大小写等。在此次实验中,使用这些方法对字符串进行操作,并观察了操作后字符串的变化;然后字符串比较,Java中可以使用equals()方法或者compareTo()方法来判断两个字符串是否相等。在这次实验中,使用这两种方法比较了不同字符串之间的关系;接着字符串格式化。Java中可以使用String.format()方法将一个字符串格式化为指定的格式。在这次实验中,使用这个方法将数字和日期格式化为指定的样式。