Przenowanie zdania
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class TaskPerf {
public static void register(String userName, String password) throws IOException {
File myObj = new File("records.txt");
if(myObj.createNewFile())
System.out.println("File Created...");
try (
FileWriter file = new FileWriter(myObj, true)) {
file.write(userName + " " + password + "\n");
}
}
public static boolean authenticate(String userName, String password) throws FileNotFoundException {
File myObj = new File("records.txt");
Scanner myReader = new Scanner (myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
String splitData[] = data.split(" ");
if (userName.equals(splitData[0]) && password.equals(splitData[1])) {
return true;
}
}
return false;
}
public static void main(String[] args)throws IOException {
Scanner scan = new Scanner(System.in);
String userName, passWord;
try {
while (true) {
System.out.println("\n---------------------------------------");
System.out.println("\nMenu");
System.out.println("1. Register");
System.out.println("2. Login");
System.out.println("0. Exit");
System.out.println("\n---------------------------------------");
int choice = scan.nextInt();
switch (choice) {
case 1 -> {
System.out.println("Username: ");
userName = scan.next();
while (!userName.matches("[a-zA-Z0-9]+")) {
System.out.println("Invalid Username.....Please type Alphanumeric characters");
System.out.println("Username: ");
userName = scan.next();
}
System.out.println("Password: ");
passWord = scan.next();
while (!passWord.matches("[a-zA-Z0-9]+")) {
System.out.print("Invalid Password.....Please type Alphanumeric characters");
System.out.println("Password: ");
passWord = scan.next();
}
System.out.println("You've succesfully registered your account!");
register(userName, passWord);
}
case 2 -> {
System.out.println("Username: ");
userName = scan.next();
System.out.println("Password: ");
passWord = scan.next();
if (authenticate(userName, passWord))
System.out.println("Successfully logged in!");
else
System.out.println("Incorrect username or password");
}
case 0 -> System.exit(0);
default -> System.out.println("Invalid Output");
}
}
}
}
Kylevincent Gutierrez