⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 logintest.java

📁 本压缩文件中含有线程的控制
💻 JAVA
字号:
package labs;

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

public class LoginTest {

	public static void main(String[] args) {
		System.out.println("This program is compiled by Zhang Yan");
		Scanner keyboard = new Scanner(System.in);
		print();

		int choice = keyboard.nextInt();
		keyboard.nextLine();
		String name;
		String password;
		int result;

		while (choice != 0) {

			if (choice == 1 || choice == 2) {
				name = getInput("Enter your name> ", keyboard);
				password = getInput("Enter the password> ", keyboard);

				if (choice == 1) {
					result = register(name, password);
					if (result == 0) {
						System.out.println("Username has already existed. ");
					} else {
						System.out.println("register successfully!!");
					}
				} else {
					result = login(name, password);
					if (result == 1) {
						System.out.println("Login successfully");

					} else if (result == 0) {
						System.out.println("Wrong password!");
					} else {
						System.out.println("Username not exists. ");
					}
				}

			}else{
				System.out.println("Wrong input!!!");
			}

			print();
			choice = keyboard.nextInt();
			keyboard.nextLine();
		}

	}

	// return 0 -- username already exists
	// return 1 -- register successfully
	public static int register(String name, String password) {

		Properties p = loadFile();
		if (p.containsKey(name)) {
			return 0;
		}

		try {
			PrintWriter pw = new PrintWriter(new FileOutputStream("users.ini",
					true));
			pw.write("\n");
			pw.write(name + "=" + password);
			pw.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 1;

	}

	// return 1 -- login success
	// return 0 -- wrong password
	// return -1 -- wrong username
	public static int login(String name, String password) {
		Properties p = loadFile();
		if (p.containsKey(name)) {
			if (password.equals(p.get(name))) {
				return 1;
			} else {
				return 0;
			}
		} else {
			return -1;
		}
	}

	public static Properties loadFile() {

		Properties p = new Properties();
		try {
			p.load(new FileInputStream("users.ini"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return p;

	}

	public static void print() {
		System.out.println("1. register");
		System.out.println("2. login");		
		System.out.println("0. exit");
		System.out.print("Enter your choice> ");
	}

	public static String getInput(String str, Scanner keyboard) {
		System.out.print(str);
		String result = keyboard.next();
		keyboard.nextLine();
		return result;

	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -