chaosillusion chaosillusion - 9 days ago 5
Java Question

How do I add more accounts and outputs to my password authentication program?

It's just as the question is titled. The area where I'm having an issue is with the if/else properties.. and also, how would I go about changing it from an API interface to an array type interface? Sorry if my formatting is poor. Feel free to correct me.

Program corrected and running how it is intended:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner; // Needed for the Scanner class

public class PasswordVerifier2 {

public static void main(String[] args) throws FileNotFoundException {

Scanner keyboard = new Scanner(System.in);
String input;

System.out.print("Please enter your password: ");
input = keyboard.nextLine();

if (authenticate1(input)) {

System.out.println("This program is working if this text is found within outputfile.txt.");

File file = new File("outputfile.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("This program is working if this text is found within outputfile.txt.");

}else if (authenticate2(input)) {

System.out.println("It works.");

}else{
System.out.println("Error: Wrong password.");
}
}

private static boolean authenticate1(String password1) {

return ((password1.length() == 6)
&& (password1.matches("beep11"))
&& (password1.matches("beep11"))
&& (password1.matches("beep11")));
}

private static boolean authenticate2(String password2) {

return ((password2.length() == 6)
&& (password2.matches("beep22"))
&& (password2.matches("beep22"))
&& (password2.matches("beep22")));
}
}

Answer

If you are using/applying one of the two methods to authenticate the user then you can use if.. else if, e.g.:

if (authenticate1(input)) {
// some code
}else if (authenticate2(input)) {
//some code
}else{
System.out.println("Error: Wrong password.");
}

EDIT

To get rid of compilation error at authenticate2, you either need to move that authenticate2 to your main class or include the class name in method call, e.g.

change

if (authenticate2(input)) {

to

if (authenticate2.authenticate2(input))

This will make sure the control does not go into second if block if first one is successful and vice versa.