fix this code? Directions: When the user chose register, only alphanumeric characters are allowed for the
Question:
fix this code?
Directions: When the user chose register, only alphanumeric characters are allowed for the input. The problem here is the user can still successfully register even if the entered input is not an alphanumeric characters or the user input no strings.
Note: Please include the screenshot of the final output. Thanks!
Existing code:
package task6;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Task6 {
private static String username;
private static String password;
private static void getUserInputs(){
Scanner usernameInput = new Scanner(System.in);
System.out.println("Enter username: ");
username = usernameInput.nextLine();
Scanner passwordInput = new Scanner(System.in);
System.out.println("Enter password: ");
password = passwordInput.nextLine();
if(!inputValidator(username) || !inputValidator(password)){
System.out.println("Only alphanumeric characters are allowed");
}
}
private static boolean authenticateUser(String details){
try {
File myObj = new File("records.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
if(data.equals(details)){
return true;
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return false;
}
private static void writeToFile(String details){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("records.txt", true));
writer.append(""+details);
writer.close();
System.out.println("User registration successful");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
private static boolean inputValidator(String input){
return input != null && input.matches("^[a-zA-Z0-9]*$");
}
public static void main(String[] args){
String register = "Register";
String login = "Login";
Scanner optionInput = new Scanner(System.in);
System.out.println("Please select your option:RegisterLogin");
String option = optionInput.nextLine();
if(option.equals(register)){
getUserInputs();
writeToFile(username+","+password);
}else if(option.equals(login)){
getUserInputs();
boolean isAuth = authenticateUser(username+","+password);
if(isAuth){
System.out.println("Successfully logged in");
}else{
System.out.println("Incorrect username or password");
}
}else{
System.out.println("Invalid option");
}
}
}
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill