本人所做的用户注册涉及以下知识:
1、Java的基本语法
2、IO输入输出流
3、List集合
4、继承、封装的知识
5、异常的涉及(本文章只涉及IO异常)
package User;
import java.io.*;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class AddUser extends User{
public void addUser()throws IOException{
File file = new File("用户信息.txt");
FileReader input = new FileReader(file);
FileWriter output = new FileWriter(file,true);
BufferedReader in = new BufferedReader(input);
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<>();
UserInformation ifm = new UserInformation();
String str;
while((str = in.readLine())!=null){
list.add(str);
}
boolean flag = false;//判断该用户是否存在
System.out.print("请输入你的名字:");
ifm.name = scanner.next();
String[] tempString = new String[5];
//判断用户是否存在
for(String person : list){
tempString = person.split(",");
if(ifm.name.equals(tempString[0])){
flag = true;
System.out.println("抱歉,该用户已存在!");
break;
}
}
//添加用户
if(flag == false){
System.out.print("请输入你的年龄:");
ifm.age = scanner.nextInt();
System.out.print("请输入你的手机号:");
ifm.phoneNumber = scanner.next();
System.out.print("请输入账号:");
ifm.account = scanner.next();
System.out.print("请输入密码:");
ifm.password = scanner.next();
User user = new User(ifm);
output.write(user.toString());
output.write("\n");
output.close();
System.out.println("用户注册成功!");
}
}
}
下面测试addUser()方法
import User.AddUser;
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
AddUser user = new AddUser();
user.addUser();
}
}
结果如下:
用户信息.txt数据如下:
本次文章就到这,谢谢大家浏览!