实验一 集合(一)
【实验目的与要求】
1、了解Java集合类的概念;
2、掌握常用集合类的使用方法和技巧,并能应用到实际操作中。
【实验内容】
1.请编写一个程序,要求如下:1)首先生成10个1至100之间的随机整数(不能重复);2)将这些数据存储到一个List集合中;3)定义个fun1(List list, int min, int max),功能为:遍历集合中的元素并删除集合list中在[min,max]间的数据;4)最后,使用Collections的sort方法对集合进行排序。
2. 请编写一个程序,要求如下:1)定义个学生类,其中包含学号、姓名、总成绩等数据及相应操作方法;2)某班级有十个学生,每个学生都有唯一的学号,在主类中,初始化十个学生的信息,并将这些对象存储于HashMap集合中(键值为学号);3)实现班级学生的按学号查询及删除功能;4)实现向集合中添加一个新学生功能。
选做题:
编写一个程序,统计List集合中指定元素出现的顺序。
【思考】
数组是很常用的一种的数据结构,我们用它可以满足很多的功能,但是,有时我们会遇到如下这样的问题:1)我们需要该容器的长度是不确定的且可变的;2)我们需要它能自动排序;3)我们需要存储以键值对方式存在的数据。因此,需要使用集合类型。
请回答List(ArrayList、LinkedList)、Set(TreeSet、HashSet)、Map(HashMap、TreeMap)类型有哪些异同。
package listUsing;
import java.util.List;
import java.util.LinkedList;
import java.util.Collections;
import java.util.Iterator;
public class Example1 {
public static void main(String[] args) {
int count = 0;
List ls = new LinkedList();
int arr[]=new int[10];
int index = 0;
while(count < 10) {
int element = (int) (Math.random()*100+1);//确保不会重复for(int i = index; i >= 0; i--){
if(arr[i] != element){
arr[index] = element;
index++;
ls.add(element);
break;
}
}
count++;
}
System.out.println("随机生成的10个数:"+ls);
Collections.sort(ls);
System.out.println("从小到大对这10个数排序:"+ls);
fun1(ls, 20, 80);
System.out.println("删除20和80之间(包括20和80)的数之后剩下的数:"+ls);
}
//遍历list,删除掉在min和max之间的数public static void fun1(List list, int min, int max) {
Iterator i = list.iterator();
while(i.hasNext()){
int x = i.next();
if(x>=min && x<=max){
i.remove();
}
}
}
public static int fun2(List ls,T t){
Iterator i = ls.iterator();
int count = 0;
while(i.hasNext()){
T x = i.next();
if(x.equals(t)){
count++;
}
}
return count;
}
/*** 使用iterator遍历集合的同时对集合进行修改就会出现java.util.ConcurrentModificationException异常* 很明显这么做是为了阻止程序员在不允许修改的时候修改对象,起到保护作用,避免出现未知异常。* iterator.remove()方法* 在iterator.remove()方法中,同样调用了ArrayList自身的remove方法,但是调用完之后并非就return了,* 而是expectedModCount = modCount重置了expectedModCount值,使二者的值继续保持相等。** */
}
package listUsing;
import java.util.HashMap;
import java.util.Iterator;
public class Class {
private HashMap stus;
public Class(){
}
public Class(HashMap stus){
setStus(stus);
}
public HashMap getStus() {
return stus;
}
public void setStus(HashMap stus) {
this.stus = stus;
}
public void insert(Student stu){
stus.put(stu.getXh(), stu);
}
public void delete(String xh){
Iterator i = stus.keySet().iterator();
while(i.hasNext()){
Student s = stus.get(i.next());
if(s.getXh().equals(xh)){
i.remove();
}
}
}
public Student select(String xh){
Iterator i = stus.keySet().iterator();
while(i.hasNext()){
Student s = stus.get(i.next());
if(s.getXh().equals(xh)){
return s;
}
}
return null;
}
public void update(){
}
}
package listUsing;
public class Student {
private String xh;
private String xm;
private double zcj;
public Student(String xh, String xm, double zcj){
setXh(xh);
setXm(xm);
setZcj(zcj);
}
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
public String getXm() {
return xm;
}
public void setXm(String xm) {
this.xm = xm;
}
public double getZcj() {
return zcj;
}
public void setZcj(double zcj) {
this.zcj = zcj;
}
}
package listUsing;
import java.util.HashMap;
public class Example2 {
public static void main(String[] args) {
Student stud1 = new Student("180512101","一",200);
Student stud2 = new Student("180512102","二",220);
Student stud3 = new Student("180512103","三",260);
Student stud4 = new Student("180512104","四",209);
Student stud5 = new Student("180512105","五",200);
Student stud6 = new Student("180512106","六",451);
Student stud7 = new Student("180512107","七",202);
Student stud8 = new Student("180512108","八",244);
Student stud9 = new Student("180512109","九",168);
Student stud10 = new Student("180512110","十",290);
HashMap stus = new HashMap();
stus.put(stud1.getXh(), stud1);
stus.put(stud2.getXh(), stud2);
stus.put(stud3.getXh(), stud3);
stus.put(stud4.getXh(), stud4);
stus.put(stud5.getXh(), stud5);
stus.put(stud6.getXh(), stud6);
stus.put(stud7.getXh(), stud7);
stus.put(stud8.getXh(), stud8);
stus.put(stud9.getXh(), stud9);
stus.put(stud10.getXh(), stud10);
Class cl = new Class(stus);
Student s = cl.select("180512105");
System.out.println("查询180512105:"+s.getXh()+" "+s.getXm()+" "+s.getZcj());
cl.delete("180512106");
System.out.println("删除180512106后:"+stus);
cl.insert(stud6);
System.out.println("添加180512106后:"+stus);
}
}
实验二 集合(二)
【实验目的与要求】
1、了解Java集合类的概念;
2、掌握常用集合类的使用方法和技巧,并能应用到实际操作中。
【实验内容】
1. 请编写一个程序,要求如下:1)定义个学生类,其中包含学号、姓名、年龄、总成绩等数据及相应操作方法;2)定义一个TreeSet类型集合用于存储某班级的10名学生对象(按学号升序存储);3)分别使用Comparable和比较器Comparator实现10名学生按年龄和按总成绩的排序,并进行输出。
2. 请基于实验一实验内容2的程序完成本内容,要求为:实现十个学生的按总成绩由大到小顺序排序及输出。提示:使用HashMap集合构造TreeMap集合。
【思考】
总结Comparable和Comparator接口的区别,并回答两者用于实现集合元素排序的编程方法分别是怎样的?
package javatest2;
import java.util.Comparator;
public class StringComparator implements Comparator {
@Override
public int compare(String s1, String s2) {
int result = s2.compareTo(s1);
return result;
}
}
package javatest2;
import java.util.Comparator;
public class Student implements Comparable {
private String xh;
private String xm;
private int nl;
private double zcj;
public Student(String xh, String xm, int nl, double zcj){
setXh(xh);
setXm(xm);
setNl(nl);
setZcj(zcj);
}
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
public String getXm() {
return xm;
}
public void setXm(String xm) {
this.xm = xm;
}
public double getZcj() {
return zcj;
}
public void setZcj(double zcj) {
this.zcj = zcj;
}
public int getNl() {
return nl;
}
@Override
public String toString() {
return "Student [学号:" + xh + ", 姓名:" + xm + ", 年龄:" + nl + ", 总成绩:" + zcj + "]";
}
public void setNl(int nl) {
this.nl = nl;
}
@Override
public int compareTo(Student stu) {
// TODO 自动生成的方法存根//根据年龄进行排序,降序int result= 0;
result = stu.nl - this.nl;
return result;
}
//用一个静态内部类实现比较器static class StudentComparator implements Comparator{
public static final int NL = 1;//年龄public static final int ZCJ = 2;//总成绩public static final int XH = 3;//学号private int orderbycolumn = 1;//默认按照年龄排序public static final boolean ASC = true;
public static final boolean DESC = false;
private boolean orderByMode = ASC; //默认升序
@Override
public int compare(Student stu1, Student stu2) {
int result = 0;
if(orderByMode) {
switch(orderbycolumn) {
case NL:
result = stu1.getNl()-stu2.getNl();
break;
case ZCJ:
result = (int)(stu1.getZcj()-stu2.getZcj());
break;
case XH:
result = stu1.getXh().compareTo(stu2.getXh());
break;
}
}else {
switch(orderbycolumn) {
case NL:
result = stu2.getNl()-stu1.getNl();
break;
case ZCJ:
result = (int)(stu2.getZcj()-stu1.getZcj());
break;
case XH:
result = stu2.getXh().compareTo(stu1.getXh());
break;
}
}
return result;
}
public int getOrderbycolumn() {
return orderbycolumn;
}
public void setOrderbycolumn(int orderbycolumn) {
this.orderbycolumn = orderbycolumn;
}
public boolean isOrderByMode() {
return orderByMode;
}
public void setOrderByMode(boolean orderByMode) {
this.orderByMode = orderByMode;
}
}
}
package javatest2;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;
import javatest2.Student.StudentComparator;
public class Main {
public static void main(String[] args) {
Student stud1 = new Student("180512101","一", 18,200);
Student stud2 = new Student("180512102","二", 19,220);
Student stud3 = new Student("180512103","三", 29,260);
Student stud4 = new Student("180512104","四", 18,209);
Student stud5 = new Student("180512105","五", 21,200);
Student stud6 = new Student("180512106","六", 20,451);
Student stud7 = new Student("180512107","七", 19,202);
Student stud8 = new Student("180512108","八", 23,244);
Student stud9 = new Student("180512109","九", 25,168);
Student stud10 = new Student("180512110","十", 24,290);
StudentComparator scomp = new Student.StudentComparator();
scomp.setOrderbycolumn(StudentComparator.XH);
scomp.setOrderByMode(StudentComparator.ASC);
TreeSet cl = new TreeSet(scomp);
cl.add(stud1);
cl.add(stud2);
cl.add(stud3);
cl.add(stud4);
cl.add(stud5);
cl.add(stud6);
cl.add(stud7);
cl.add(stud8);
cl.add(stud9);
cl.add(stud10);
System.out.println("按照学号升序排列:");
Iterator i = cl.iterator();
while(i.hasNext()) {
Student stu = i.next();
System.out.println(stu);
}
TreeSet cl2 = new TreeSet();
cl2.addAll(cl);
System.out.println("按照年龄降序排列:");
i = cl2.iterator();
while(i.hasNext()) {
Student stu = i.next();
System.out.println(stu);
}
StudentComparator scomp2 = new Student.StudentComparator();
scomp2.setOrderbycolumn(StudentComparator.ZCJ);
scomp2.setOrderByMode(StudentComparator.DESC);
TreeSet cl3 = new TreeSet(scomp2);
cl3.addAll(cl);
System.out.println("按照成绩降序排列:");
i = cl3.iterator();
while(i.hasNext()) {
Student stu = i.next();
System.out.println(stu);
}
HashMap stus = new HashMap();
stus.put(stud1.getXh(), stud1);
stus.put(stud2.getXh(), stud2);
stus.put(stud3.getXh(), stud3);
stus.put(stud4.getXh(), stud4);
stus.put(stud5.getXh(), stud5);
stus.put(stud6.getXh(), stud6);
stus.put(stud7.getXh(), stud7);
stus.put(stud8.getXh(), stud8);
stus.put(stud9.getXh(), stud9);
stus.put(stud10.getXh(), stud10);
StringComparator sc = new StringComparator();
TreeMap tm = new TreeMap(sc);
tm.putAll(stus);
System.out.println("使用TreeMap来实现按id降序排列");
Iterator i2 = tm.keySet().iterator();
while(i2.hasNext()) {
Student stu = tm.get(i2.next());
System.out.println(stu);
}
}
}
实验三 Java输入与输出
【实验目的与要求】
1、掌握常用字节输入输出流的用法;
2、掌握常用字符输入输出流的用法;
3、掌握File类的用法。
【实验内容】
1. 请编写一个程序,使用FileInputStream与FileOutputStream流实现文件的拷贝,具体要求如下:
a) 将当前程序源文件(MyIoExc.java)的内容拷贝到E:\shiyan3路径下的文件名为mycopy.txt的文件中(拷贝文件中所有的内容);拷贝完成,在命令行窗口中提示拷贝成功;
b) 读取mycopy.txt文件,并在命令行窗口中显示文件的全部内容。
提示:1)对于不存在的路径可使用File类型先创建好;2)接收的数组可构造String文件不确定源文件中数据多少时可使用循环读取数据;如何判断文件中是否还有数据(read方法的返回值-1)。
2. 请基于内容1的程序做修改,使用FileReader与FileWriter流实现文件的拷贝。请理解并熟练掌握基本字节和字符流的区别和用法。
3. (选做题)现有一个文件english.txt,请使用缓冲流(BufferedReader、BufferedWriter)完成本程序,具体要求如下:读取文件中的内容,统计其中每一行单词的个数,并同时将每一行的单词个数及每个单词写到另一个文件中。
(可参考”实用”例10_7)
例如:“第1行共5个单词,分别为:The,arrow,missed,the,target;”
提示:字符串分割可使用split方法(正则表达式中,空格类字符、英文输入法下符号的元字符为:”\s”、”\p{Punct}”)、StringTokenizer或者Scanner类型实现。
【思考题】
1.String与字节数组(字符数组)间相互转换的方法是什么?
2.请查阅资料总结字节输入输出流和字符输入输出流的含义和使用上的区别,并分别说明教材中的各种流类型的特点和使用中的特殊之处。
package javatest3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**** @author cust*拷贝云文件到mycopy.txt中*/
public class Copy {
public static void main(String[] args) {
File fl1 = new File("E:\\课程\\Java\\下学期实验课\\实验三\\javatest3\\src\\javatest3\\Copy.java");
//要拷贝的文件File fl2 = new File("D:\\shiyan3\\mycopy.txt");
//拷贝文件File path;//记录文件路径//判断文件的路径是否存在,不存在就创建路径if(!(path = new File(fl2.getParent())).exists()){
path.mkdirs();
}else{
if(!fl2.exists()){//文件不存在就创建文件try {
fl2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//System.out.println(path);copy(fl1, fl2);//执行拷贝函数}
FileInputStream input;
try {
input = new FileInputStream(fl2);
byte[] buf = new byte[1024]; //用于接受读入的二进制数据 int bytesRead; //读入长度 while ((bytesRead = input.read(buf)) > 0) { //仍有数据读入 //如果read返回-1,则文件中无数据了 String str = new String(buf, 0, bytesRead);
//如果未读入完,那么就不能构建出str,也就不能输出,所以我们需要指定长度 System.out.println(str);
}
} catch (Exception e) {
// TODO Auto-generated catch blocke.printStackTrace();
} //读入流
}
/**** @param oldfile要拷贝的文件* @param newfile拷贝到的文件* 通过InputStream,OutputStream等字节流或者FileReader、FileWriter等字符流来实现拷贝。* 循环遍历oldfile文件的内容,拷贝到newfile文件中。*/
public static void copy(File oldfile, File newfile){
InputStream input = null;
OutputStream output = null;
try{
input = new FileInputStream(oldfile); //读入流 output = new FileOutputStream(newfile); //写入流 byte[] buf = new byte[1024]; //用于接受读入的二进制数据 int bytesRead; //读入长度 while ((bytesRead = input.read(buf)) > 0) { //仍有数据读入 //如果read返回-1,则文件中无数据了 output.write(buf, 0, bytesRead); //写入文件 }
System.out.println("拷贝成功");//输出提示信息 input.close();
output.close();
} catch (Exception e) {
// TODO Auto-generated catch blocke.printStackTrace();
}
//try {//FileReader fr = new FileReader(oldfile);//FileWriter fw = new FileWriter(newfile);//char[] chs = new char[512];// int charsRead; //读入长度// while ((charsRead = fr.read(chs)) > 0) { //仍有数据读入// fw.write(chs, 0, charsRead); //写入文件// }// fr.close();// fw.close();} catch (Exception e) {//e.printStackTrace();//}
}
}
/*** 1.mkdirs()和 mkdir()的对象都是路径,不是文件,时刻牢记。* 2.通过exists()函数判断是否存在**/
package javatest3;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CountWord {
public static void main(String[] args) {
File english = new File("C:\\Users\\cust\\workspace\\javatest3\\src\\english.txt");
File count = new File("D:\\shiyan3\\count.txt");
File path;//记录文件路径if(!(path = new File(count.getParent())).exists()){
path.mkdirs();
}else{
if(!count.exists()){//文件不存在就创建文件try {
count.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//System.out.println(path);countWords(english, count);
}
}
/**** @param file原英文文档* @param newfile记录英文文档个数的文件* 将原英文文档每行的单词个数以及这些单词,写入另一个文件中。* 通过BufferedReader、BufferedWriter实现*/
public static void countWords(File file, File newfile){
try {
//文件读入FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(newfile);
BufferedWriter bw = new BufferedWriter(fw);
//这里如果写上第二个参数就是追加模式,不会清空原文档String str;
int count = 0;
int row = 1;
while ((str = br.readLine()) != null) { //仍有数据读入 String[] s = str.split("[^a-zA-Z]");
String info = null ;
//如果未读入完,那么就不能构建出str,也就不能输出,所以我们需要指定长度 for(int i = 0; i< s.length; i++){
if(s[i] != ""){
count++;
}
}
info="第"+row+"行有"+count+"个单词,分别是:";
for(int i = 0; i< s.length; i++){
if(s[i] != ""){
info += s[i]+" ";
}
}
System.out.println(info);
//info += "\r\n";//换行 bw.write(info);
bw.newLine();//BufferedWriter对象中可以通过newLine()进行换行 row++;
count = 0;
}
br.close();
fr.close();
bw.close();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
实验四 Swing程序设计(1)
【实验目的与要求】
1、理解容器和组件的思想,掌握Swing开发图像用户界面程序的方法;
2、理解布局的概念及掌握几种布局管理器特点和用法;
3、理解Java的消息处理机制,掌握消息处理方法。
【实验内容】
1. 编写一个应用程序,其中有一个窗口,标题为“求和”,具体地:
a) 窗口布局为BorderLayout;在窗口的北侧区域包含有一个文本框和一个按钮,窗口中间区域有一个文本区。
b) 每当用户在文本框中输入一个数值并回车时,该数值显示在文本区中(空格分隔,每行显示5个数值);当用户输入“c”的时候,清空文本区的全部内容。
c) 当用户点击按钮时,统计并显示文本区中全部数据的个数并求和。
2.(选做题)编写一个程序,可将某文件中的内容读入程序中,并在窗口中的文本区进行显示;在修改文本区内容后,可将修改后的内容再写入该文件中。
【思考题】
1.请列出监听接口(ActionListener等)有哪些,并写出每个接口可以监听哪些组件的什么事件?
2.FlowLayout和BorderLayout在布局式样和用法上有什么不同?
3.总结Java事件处理程序的编写步骤。
package main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JTextArea;
public class ReadActionListener implements ActionListener{
private File fl;//要写入的文件private JTextArea jta;//追加的区域
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根this.readFile(fl);
}
public File getFl() {
return fl;
}
public void setFl(File fl) {
this.fl = fl;
}
public JTextArea getJta() {
return jta;
}
public void setJta(JTextArea jta) {
this.jta = jta;
}
/**** @param oldfile要拷贝的文件* 通过BufferedReader字符流来实现读取文件。* 解决了中文乱码问题* Reader 类是 Java 的 I/O 中读字符的父类,* 而 InputStream 类是读字节的父类,* InputStreamReader 类就是关联字节到字符的桥梁,* 它负责在 I/O 过程中处理读取字节到字符的转换,* 而具体字节到字符的解码实现它由 StreamDecoder 去实现,* 在 StreamDecoder 解码过程中必须由用户指定 Charset 编码格式。* 值得注意的是如果你没有指定 Charset,将使用本地环境中的默认字符集,例如在中文环境中将使用 GBK 编码。** 总结* Java读取数据流的时候,一定要指定数据流的编码方式,* 否则将使用本地环境中的默认字符集。*/
public void readFile(File oldfile){
try {
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(oldfile),"GBK"));
String line = null;
jta.setText("");
while ((line = br.readLine()) != null) {
jta.append(line+"\n");
}
System.out.println("读取成功");
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.swing.JTextArea;
/**** @author 23820* 输出监听器,用于指定写入指定文件的功能**/
public class WriteActionListener implements ActionListener{
private File fl;//要写入的文件private JTextArea jta;//追加的区域
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根this.writeFile(fl);
}
public File getFl() {
return fl;
}
public void setFl(File fl) {
this.fl = fl;
}
public JTextArea getJta() {
return jta;
}
public void setJta(JTextArea jta) {
this.jta = jta;
}
/**** @param newfile拷贝到的文件* 通过OutputStream等字节流将文本域中的内容写入指定文件*/
public void writeFile(File newfile){
OutputStream output = null;
try{
output = new FileOutputStream(newfile); //写入流 byte[] buf = jta.getText().getBytes(); //用于接受读入的二进制数据 output.write(buf, 0, buf.length); //写入文件 System.out.println("写入成功");//输出提示信息 output.close();
} catch (Exception e) {
// TODO Auto-generated catch blocke.printStackTrace();
}
}
}
package main;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Sum extends JFrame{
/****/
private static final long serialVersionUID = 1L;
private JPanel jp;//输入部分private JTextField jtf;//文本框private JButton jb;//求和按钮private JTextArea jta;//求和按钮private final BorderLayout bl = new BorderLayout();//边界布局final JScrollPane scrollPane = new JScrollPane();//滚动框int colums = 0;//记录当前的数字的行位,5个换行int count = 0;//记录数据个数
public Sum(){
super();//构造窗体
setBounds(400, 300, 500, 340);
setTitle("求和");//设置标题Container c = getContentPane();//获取可操作部分c.setLayout(bl);//设置布局为边界布局setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭方式
jtf = new JTextField();//构造输入部分jtf.setColumns(20);
jtf.setHorizontalAlignment(JTextField.LEFT);
jtf.setFont(new Font("", Font.BOLD, 12));
jb = new JButton("显示数据个数并求和");
jp = new JPanel();
jp.add(jtf);
jp.add(jb);
jta = new JTextArea();//构造显示部分jta.setLineWrap(true);
scrollPane.setViewportView(jta);
c.add(jp, BorderLayout.NORTH);
c.add(scrollPane, BorderLayout.CENTER);
jtf.addActionListener(new ActionListener(){
/*** 添加键盘事件,输入c清空,每5个换行* 将文本框中的加入文本区中,用空格分割*/
@Override
public void actionPerformed(ActionEvent e) {
String str = jtf.getText();
colums++;
if(str.equals("c")){
jta.setText("");
count = 0;
colums = 0;
}else{
if(colums == 5){
jta.append(str+"\n");
colums = 0;
}else{
jta.append(str+" ");
}
count ++;
}
jtf.setText("");
}
}
);
jb.addActionListener(new ActionListener(){
/*** 显示数据个数并求和*/
@Override
public void actionPerformed(ActionEvent arg0) {
int sum = 0;
String[] numbers = jta.getText().split("\n");
for(int i = 0; i
String []nu = numbers[i].split(" ");
for(int j = 0; j < nu.length; j++){
sum += Integer.parseInt(nu[j]);
}
}
jta.setText("");
jta.append("数据共"+count+"个,总计"+sum);
}
}
);
setVisible(true);//显示可见 }
public static void main(String[] args) {
new Sum();
}
}
package main;
import java.awt.BorderLayout;
import java.awt.Container;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class IOFile extends JFrame{
private JPanel jp;//输入部分private JButton jb2;//操作按钮private JButton jb1;//操作按钮private JTextArea jta;//文本内容显示区private final BorderLayout bl = new BorderLayout();//边界布局final JScrollPane scrollPane = new JScrollPane();//滚动框private File fl;
public static void main(String[] args) {
IOFile io = new IOFile();
JFileChooser fd = new JFileChooser();
//fd.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);fd.showOpenDialog(null);
io.fl = fd.getSelectedFile();
ReadActionListener ral = new ReadActionListener();
ral.setFl(io.fl);
ral.setJta(io.jta);
io.jb1.addActionListener(ral);
WriteActionListener wal = new WriteActionListener();
wal.setFl(io.fl);
wal.setJta(io.jta);
io.jb2.addActionListener(wal);
}
public IOFile(){
super();//构造窗体
setBounds(400, 300, 500, 340);
setTitle("修改文件内容");//设置标题Container c = getContentPane();//获取可操作部分c.setLayout(bl);//设置布局为边界布局setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭方式
jb1 = new JButton("读入文件");
jb2 = new JButton("写入文件");
jp = new JPanel();
jp.add(jb1);
jp.add(jb2);
jta = new JTextArea();//构造显示部分jta.setLineWrap(true);
scrollPane.setViewportView(jta);
c.add(jp, BorderLayout.NORTH);
c.add(scrollPane, BorderLayout.CENTER);
setVisible(true);//显示可见}
}