这几天,一直在忙着写java大作业,想总结一下这次作业学到的东西。
定义member类
//定义member类
package com.homework;
public class Member {
private String num;
private String name;
private String phone;
public Member(String num,String name,String phone) {
this.num=num;
this.name=name;
this.phone=phone;
}
public String getNum() {
return this.num;
}
public String getName() {
return this.name;
}
public String getPhone() {
return this.phone;
}
public void setNum(String num) {
this.num=num;
}
public void setName(String name) {
this.name=name;
}
public void setPhone(String phone) {
this.phone=phone;
}
public String toString() {
return "编号: "+this.num+" 姓名: "+this.name+" 电话号: "+this.phone;
}
}
memberSystem类中有关定义
Member arr[]=new Member[1000];
private int x=0;
1.时间延迟函数
Thread.currentThread();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
2.文件读写
将member数组写入TXT文件中
//将member数组写入TXT文件中
public class MemberSystem {
Member arr[]=new Member[1000];
private int x=0;
private int s=0;
private int n=0;
private int a=0;
Scanner in=new Scanner(System.in);
public void writeTxt() {
boolean b=false;
File fMember=new File("member.txt");
if(!fMember.exists()) {
b=false;
try {
b=fMember.createNewFile();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(b) {
System.out.println("信息已保存");
}
}
}
try {
Writer w=new FileWriter(fMember);
w.write(toStringMember());
w.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("保存完成");
}
toStringMember函数
public String toStringMember() {
String str="";
for(int i=0;i<x;i++) {
str=str+arr[i].toString()+"\r\n";
}
return str;
}
addMember函数
public void addMember(String num,String name,String phone) {
arr[x]=new Member(num, name, phone);
x++;
}
从TXT文件中读取数组元素
public void readMember() {
String pathname = "member.txt";
try (FileReader reader = new FileReader(pathname);
BufferedReader br = new BufferedReader(reader)
) {
String line;
while ((line = br.readLine()) != null) {
String[] st=line.split(" ");
arr[x]=new Member("","","");
arr[x].setName(st[3]);
arr[x].setNum(st[1]);
arr[x].setPhone(st[5]);
x++;
//this.addMember(st[1], st[3], st[5]);
}
} catch (IOException e) {
e.printStackTrace();
}
}