I am trying to complete an authentication program for my final project. I am checking for user authentication, if the user info doesn't match the credentials file, the output tells them this and then prompts for username and password while increment an attemptCounter. The only portion I am experiencing an issue with is when I test and incorrect attempt followed by a correct attempt, the while loop will not restart my authentication procedure, instead it simple says incorrect login again. Why isn't my continue statement restarting my while loop iteration?
I tired looking around for this answer on the forum and food nothing specific to my issue. I tried moving my conditional statement as well to see if it was in the wrong spot for my continue to work but it fixed nothing. Compiler says both of my continue statements are unnecessary.
//prompting user for username
System.out.println("Please enter your username (\"L\" to logout \"Q\" to quit): ");
username = scnr.nextLine();
//evaluating if user wants to quit immediately
if(username.equals("Q")) {
System.exit(0);
}
//prompting user for password and storing to password field
System.out.println("Please enter your password: ");
password = scnr.nextLine();
System.out.print("\n");
//while loop that contains the authentication and authorization logic
while (!username.equals("Q") && attemptCounter < 2){
//calling of hashInput method of MD5Hash class to return the hashed user password
userHashedPassword = userHash.hashInput(password);
//while loop to open the credentials for authentication comparison
while (cfScnr.hasNextLine()) {
//assigning the files scanned next line to a field for comparison
line = cfScnr.nextLine();
//conditional statement to determine if username and password are contained on the line
//will break file loop as soon as line contains the user's username and password
//statement logic used to return the role string and remove extra characters and white space
if (line.contains(username) && line.contains(userHashedPassword)) {
dqLocation = line.lastIndexOf('"');
role = line.substring(dqLocation);
role = role.replaceAll("\\s+", "");
role = role.replace("\"", "");
break;
}
}
//conditional statement used to determine if previous loops condtional statement was meant
//if it wasn't this condition will inform the user of incorrect username and/or password
//inform them of attempts remaining and prompt them for a new username and password while
//tracking the attempts and it they want to quit. If Q isn't entered main while loop will restart authentication
if (role == null){
attemptCounter++;
System.out.println("Username or password incorrect. " + (3 - attemptCounter) + " attempts remaining.");
System.out.println("Please enter your username (\"L\" to logout \"Q\" to quit): ");
username = scnr.nextLine();
if(username.equals("Q")) {
System.exit(0);
}
System.out.println("Please enter your password: ");
password = scnr.nextLine();
continue;
}
//this conditional statement runs only when the user is authenticated
else {
//creating new file object and scanner object to scan the role file
File rFile = new File("src\\zooauthenticationsystem\\" + role + ".txt");
Scanner rfScnr = new Scanner(rFile);
//while loop to parse through the role file and output the lines of the file to the console
while (rfScnr.hasNextLine()){
rolePrint = rfScnr.nextLine();
System.out.println(rolePrint);
}
//prompting user if they would like to logout or simply quit the program
System.out.println("\nPress \"L\" to logout and \"Q\" to quit.");
userDecision = scnr.nextLine();
//conditional statement to determine their input, and resetting role to null to reset authentication loop conditional statements, restarts main while loop
if (userDecision.equals("L")){
System.out.println("Please enter your username: ");
username = scnr.nextLine();
if(username.equals("Q")) {
System.exit(0);
}
System.out.println("Please enter your password: ");
password = scnr.nextLine();
System.out.print("\n");
role = null;
continue;
}
Let's get rid of most of your code, let's format the code better, and let's leave only the control structures to see what the continue statements are doing:
while (!username.equals("Q") && attemptCounter < 2) {
userHashedPassword = userHash.hashInput(password);
while (cfScnr.hasNextLine()) {
line = cfScnr.nextLine();
if (line.contains(username) && line.contains(userHashedPassword)) {
// ... do some stuff
break;
}
}
if (role == null) {
// ... do some stuff
continue; // **** (A) ****
} else {
// ... do some stuff
if (userDecision.equals("L")){
// ... do some stuff
continue; // **** (B) ****
}
}
}
If line (A) is reached, you're in the if (roll == null) block, the else will never be entered, and the while loop will repeat regardless of the continue statement making continue unnecessary and distracting.
Likewise if line (B) is reached, you're in the last control block of the while loop, and so the loop will continue regardless of the continue statement making continue unnecessary and distracting.
Related
I was trying to build a simple UI where a user enters a username and if the username is xyz then the user will be shown "enter your password". If the password is xyz1234 then the user will be shown "please wait loading..." and the scanner exits. If the username was incorrect, I tried to code it in a way so that it keeps asking for the username until the correct username is entered.
Apparently, the first part of the code works, if the username is xyz, then the code works correctly and displays what i want it to. However if the username is wrong in the first attempt and right in the second attempt, it still continues to show "incorrect username" instead of showing "enter the password".
The code is shown below:
import java.util.Scanner;
class User_Authentication
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter your Username");
String username=in.nextLine();
if(username.equals("xyz"))
{
System.out.println("Enter the Password");
String password=in.nextLine();
if(password.equals("xyz1234"))
{
System.exit(0);
System.out.println("Welcome");
System.out.println("Please wait while the system is loading....");
}
else
{
System.out.println("Your system has been locked for security reasons.");
System.out.println("Please contact an administrator to reset the password");
System.out.println("Any attempt to break in the computer will result in self destruction.");
System.exit(0);
}
}
else
{
do
{
if(username.equals("xyz"))
{
break;
}
System.out.println("Incorrect username");
System.out.println("Please try again");
in.nextLine();
}
while((username.equals("xyz"))==false);
}
}
} ```
Your saying in.nextLine() in your do-while loop, rather than username = in.nextLine()
Replace that and it should work, but overall you're do-while loop needs some work, it's relatively messy. Here's how I would approach it.
do {
System.out.println("Incorrect username");
System.out.println("Please try again");
username = in.nextLine();
} while(username.equals("xyz") == false);
I'm a Java beginner and my project consists of creating a simple program to register users for an alumni center. The process creates an ID and then provides the new user with an OTP. Next is the login (Enter ID:, Enter OTP: ).
My OTP verification method is not working. It seems to be a problem with the IF.equals declaration, the process jumps straight to the ELSE condition.
Any suggestions why?
Here is my code:
class Main {
static NewRegandLogin newRegAndLogin = new NewRegandLogin(null, null, null, null, null, null);
static ArrayList<NewRegandLogin> loginInformation = new ArrayList<>();
public static void main(String[] args) {
System.out.println(" WELCOME TO THE ALUMNI SHE-CODES SYSTEM ");
System.out.println("_________________________________\n - New Alumni registration - \n");
System.out.println("");
newRegAndLogin.registerNewGrad();
System.out.println();
System.out.println("_________________________________");
System.out.println();
System.out.println("Your new Alumni ID is: " + newRegAndLogin.getAlumniId());
System.out.println();
System.out.println("Your temporary password is:");
System.out.println(newRegAndLogin.oTp(8));
loginInformation.add(newRegAndLogin);
System.out.println("_________________________________");
System.out.println("_________________________________\n - Alumni Login - \n");
System.out.println("");
newRegAndLogin.login();
System.out.println("");
System.out.println("Please make a list of completed Courses: -->Enter 'S' to stop adding courses<--");
newRegAndLogin.setAlumniCourses();
System.out.println("_________________________________");
newRegAndLogin.setLinkedInPage();
loginInformation.add(newRegAndLogin);
//printAlumniProfile();
System.out.println("_________________________________");
newRegAndLogin.jobOffer();
}
void login() {
System.out.print("ID: ");
alumniIdImput = scanner.nextLine();
idVerification();
do {
System.out.println("Password (OTP if logging in for the first time): ");
passwordImput = scanner.nextLine();
oTpFromImput = passwordImput.toCharArray();
oTpVerification();
} while (isPasswordCorrect=false);
void oTpVerification() {
isPasswordCorrect = false;
if (oTpFromImput.equals(oTp(8))) {
isPasswordCorrect = true;
System.out.println("Logging In.....");
}else {
isPasswordCorrect = false;
System.out.println("Incorrect password.\nPlease enter valid password: 8 alpha numeric
characters(Aa,123,#,#,$,%)");
}
}
This is the oTp method
char[] oTp (int length) {
String capitalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String smallChars = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String symbols = "!##$%^&*_-=+/.?<>";
String values = capitalChars + smallChars + numbers + symbols;
Random oneTimePassword = new Random();
char[] password = new char[length];
for(int i = 0; i<length;i++) {
password[i] = values.charAt(oneTimePassword.nextInt(values.length()));
}
return password;
}
It seems you built a guessing game, not an OTP verification code.
You first read the OTP from user, and only then randomly generate one to copare to it.
Basically, you code expects the user to guess a random 8 character password that has not been created you, which is basically impossible...
You need to generate to OTP first, show it to the user, then ask them to input it.
I see your logic code is generate OTP code after User input. It seem so wierd bro.
Whenever you call oTp(8) function will generate new OTP.
Use should generate OTP first then store somewhere, then User input and compare it.
You need to store the generated otp somewhere. Then compare it with the input otp. Right now you are comparing it with the otp(8). And otp(8) always returns a new otp.
I'm working on a Java project, building a simple system, and it has some methods, one of them is "Change PassWord", I put the user's information (username & password) in a text file called ("Users.txt").
Now this is the description of the method:
boolean ChangePassWord(): Asks the user to enter old password for
verification, the user has at maximum three tries to enter correct old
password; if not the password will not be changed and a message Box
will be shown for the user. If user entered correct old password then
he is authenticated to changer his password and asked to enter new
password and confirming the new. Once if confirmed correctly the old
password will be changed to the new one and a message box will be
shown if wrong confirmation the old password will not be changed and a
message box will be shown.
I wrote this code:
boolean changePassword(){
String pass=JOptionPane.showInputDialog(null, "Enter old password: ", "Input", JOptionPane.QUESTION_MESSAGE);
if(pass.equals(Password)) {
String newpass=JOptionPane.showInputDialog(null,
"Enter new password: ", "Input", JOptionPane.QUESTION_MESSAGE);
String connewpass=JOptionPane.showInputDialog(null,
"Enter confirming new password: ", "Input",
JOptionPane.QUESTION_MESSAGE);
if(newpass.equals(connewpass)){
Password= newpass;
JOptionPane.showMessageDialog(null, "password changed ", "message",
JOptionPane.INFORMATION_MESSAGE);
return true;
}
else
JOptionPane.showMessageDialog(null, "Wrong Conferm ", "message",
JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "Wrong password ", "message",
JOptionPane.INFORMATION_MESSAGE);
return false;
}
but I think that it's wrong, and I need to use a loop I think.
I hope you help me!
A while loop is appropriate for your case. I will briefly explain how this while loop runs 3 times.
So, first n=3. The condition n-- > 0 means 2 things. Check if n is greater than zero and subtract the value of n by 1. These 2 things happen in that exact order.
So the condition checks that n is indeed greater than zero and enters the loop. At the same time n is also decreased by 1 and becomes 3-1=2.
This goes on 3 times. After the 3rd time, n becomes 0. And the condition 0 > 0 is false and therefore the while loop breaks.
boolean changePassword(){
String pass = ""; //get old password from user
int n = 3;
while (n-- > 0) {
if(pass.equals(Password)) {
String newPass = ""; // get new password from user
String conNewPass = ""; // confirm new password from user
if (newPass.equals(conNewPass)) {
Password = newPass;
// password changed
return true;
} else {
// wrong confirmation.. password not changed
return false;
}
}
else {
// tell user to enter the correct old password
pass = ""; // ask user for old password again
}
}
// show error message that user entered the old password 3 times incorrectly
// and return false
return false;
}
// My Scanner
Scanner input = new Scanner(System.in);
//using Do While Loop
do {
//Asking user to enter email
System.out.println("enter your email:");
//Read and safe input in to Var userEmail
String userEmail = input.next();
//Check for contains '#' and '.com' simbols
Pattern pattern = Pattern.compile("\\S+?#\\S+?\\.com");
//And it checking in users entered email
Matcher matcher = pattern.matcher(userEmail);
//if userEmail contain '#'and '.com' print next line
if (matcher.matches()) {
System.out.println("Matches"); // Prints this for this email
}
//if user put email with out '#'and'.com' print next line
else {
System.out.println("your email should
looks like this sample bob.Dillon#gmail.com");
}
// And here I have a problem don't know what to type in
// so that it starts looping until user input will be 100% correct.
} while(!matcher.matches());
Can someone help what needs to be done here while(here); to make it looping?
You want to see if the user entered anything in those fields. So, check like this:
if (INPUTVALUE.length > 0) { //THEY ENTERED SOMETHING
// do something
}
Then, put this in your while statement. Like so:
// My Scanner
Scanner input = new Scanner(System.in);
//using Do While Loop
do{
//Asking user to enter email
System.out.println("enter your email:");
//Read and safe input in to Var userEmail
String userEmail = input.next();
//Check for contains '#' and '.com' simbols
Pattern pattern = Pattern.compile("\\S+?#\\S+?\\.com");
//And it checking in users entered email
Matcher matcher = pattern.matcher(userEmail);
//if userEmail contain '#'and '.com' print next line
if (matcher.matches()) {
System.out.println("Matches"); // Prints this for this email
}
//if user put email with out '#'and'.com' print next line
else{
System.out.println("your email should
looks like this sample bob.Dillon#gmail.com");
}
//And here I have a problem don't know what to type in so that it starts looping until user input will be 100% correct
}while(INPUTVALUE.length > 0);
You need:
}while(INPUTVALUE.length > 0);
To break the loop:
Just erase all of the values that the user has entered at the end of the do. That way, INPUTVALUE.length < 0. That will break the loop ! Good luck !
I have a client-server console based application, in client side I have used switch statement for selecting options such as upload/ download/ change password etc. When user enters one number for suppose
String userchoice = console.readLine("Enter your choice :");
int choice= Integer.parseInt(userchoice);
switch (choice){
case 3:
........
Socket soc = new Socket("localhost", 6007);
String reply;
String client = username;
char newpswd[] = console.readPassword("Enter your new Password :");
String newpwd=new String(newpswd);
char newpswd1[] = console.readPassword("Confirm your new Password :");
String newpwd1=new String(newpswd1);
if(newpwd.equals(newpwd1)) {
........
}
else {
S.O.P ("Passwords don't match");
}
break;
After the process has been finished, then I need to send the user to switch (choice) statement again asking for the option number to enter. I have tried continue, return but none worked for me. return - will return to JVM I suppose, which is exiting the program. As goto is not used in Java, what will be my alternative ?
After the process has been finished, then I need to send the user to switch (choice) statement again
Then you need a loop:
while (!quit) {
String userchoice = console.readLine("Enter your choice :");
...
switch (...) {
...
}
}
do {
...
}while(choice != EXIT_CHOICE);
where EXIT_CHOICE is a constant
You can use a while loop, which will execute until it's condition is false or until it is broken from within.
while (some condition) {
String userchoice = console.readLine("Enter your choice :");
......
if (some case is met) {
break;
}
}
It does not work this way. When you get to a switch, it decides (based in the expression evaluated, and the choices present) which will be the next op to be executed, and does nothing more (that is why you need the break statement to avoid running into the next bunch of code).
Get the switch into a loop or a function that gets called twice.
You could put it all in a method that returns a boolean, true if the passwords matched, false if not. Then you could use something like:
boolean loginSuccess = false;
while (!loginSuccess) {
loginSuccess = loginMethod();
}
Edit
Or you could use a do loop...
do {
String userchoice = console.readLine("Enter your choice :");
int choice= Integer.parseInt(userchoice);
switch (choice){
case 3:
........
Socket soc = new Socket("localhost", 6007);
String reply;
String client = username;
char newpswd[] = console.readPassword("Enter your new Password :");
String newpwd=new String(newpswd);
char newpswd1[] = console.readPassword("Confirm your new Password :");
String newpwd1=new String(newpswd1);
} while (!newpwd.equals(newpwd1));