java IO实现简单注册登录功能

java IO实现简单注册登录功能

  • 实例如下:

实例如下:

import java.io.*;
import java.util.*;

class User{
	private String userName, password;
	public User(){}
	public User( String userName, String password ){
		this.userName = userName;	this.password = password;		
	}
	public void setUserName( String userName ){
		this.userName = userName;
	}
	public String getUserName(){
		return userName;
	}
	public void setPassword( String password ){
		this.password = password;
	}
	public String getPassword(){
		return password;
	}
}

interface UserDao{
	void registUser( User user )throws IOException;
	boolean loginUser( User user )throws IOException;
}

class UserDaoImpl implements UserDao{
	public static File file = new File( "user.txt" );
	public void registUser( User user )throws IOException{
		String info = user.getUserName() + "=" + user.getPassword();
		BufferedWriter bw = new BufferedWriter( new FileWriter( "user.txt", true ) );
		bw.write( info );	bw.newLine();	bw.flush();	bw.close();
	}
	public boolean loginUser( User user )throws IOException{
		boolean isRegistered = false;
		BufferedReader br = new BufferedReader( new FileReader( "user.txt" ) );
		String s;
		while( (s = br.readLine()) != null ){
			String[] strs = s.split( "=" );
			if( strs[0].equals( user.getUserName() ) && strs[1].equals( user.getPassword() ) ){
				isRegistered = true;
			}
		}
		return isRegistered;
	}
}

class GuessNumber{
	public static void playGame(){
		int randomNumber = (int)( Math.random() * 100 ) + 1; 
		Scanner sc = new Scanner( System.in );
		System.out.println( "请输入所猜的数字:" );
		int number;
		while( (number = sc.nextInt()) != randomNumber ){
			System.out.println( number > randomNumber ? "大了,请继续输入:" : "小了,请继续输入" );
		}
		System.out.println( "恭喜猜对了!" );	
	}
}
public class Test0622{
	public static void main( String[] args )throws IOException{
		Scanner sc = new Scanner( System.in );
		System.out.println( "欢迎来到注册登录界面!" + "\n" +
			"1.注册" + "\n" + "2.登录" + "\n" + "3.退出" );
		String s;
		UserDaoImpl udi = new UserDaoImpl();
		while( ! (s = sc.nextLine()).equals( "3" ) ){
			int n = Integer.parseInt( s );
			switch( n ){
			case 1:
				System.out.print( "欢迎来到注册界面!" + "\n" + "请输入用户名: " );
				String userName = sc.nextLine();
				System.out.print( "请输入密码: " );
				String password = sc.nextLine();
				User user = new User( userName, password );
				udi.registUser( user );
				System.out.println( "注册成功!" );
				break;
			case 2:
				System.out.println("欢迎来到登录界面!" + "\n" + "请输入用户名: " );
				String inputUserName = sc.nextLine();
				System.out.print( "请输入密码: " );
				String inputPassword = sc.nextLine();
				User inputUser = new User( inputUserName , inputPassword );
				if( udi.loginUser( inputUser ) ){
					System.out.println( "登录成功,可以玩游戏了!" );
					GuessNumber.playGame();
				}
				else	System.out.println( "登录失败!" );
				break;
			case 3:	System.exit( 0 );
				break;
			default:	break;
			}
		}
	}
}

你可能感兴趣的:(java随记)