I'm new to Java and thought I would make one of the classic Username and Password validation programs which I have successfully made with no obvious bugs, however I would like the program to essentially restart the input if the user enters the in-correct information. How would I go about restarting the program successfully each time the users enters wrong information?
Code below:
import java.util.Scanner;
public class UserPass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user; //Creating user-name variable.
String pass; //Creating password variable.
System.out.println("Enter username here: "); //Message to tell user to input the user-name.
user = input.nextLine(); //Taking the users user-name input.
System.out.println("Enter the password here: "); //Message to tell user to input the password.
pass = input.nextLine(); //Taking the users password input.
//Validating the users User-name and password input.
if(user.equals("Shane") && (pass.equals("Temple"))) {
System.out.println("Correct!"); //If the User-name and password are both correct then a message will tell the user that they are correct.
}
else {
System.out.println("The Usernname or Password that you have entered was in-correct"); //If above conditions are not met then message will tell the user that they have entered the wrong user-name or password
}
}
}
I know this is extremely basic as I said I'm very new to Java (2 hours ago new).
I thought of calling the "main" method inside the else condition statement however I heard It's bas practice to use the "main" method any more times than when the program first starts.
Thanks in advance :)
I hope this is what you wanted.
import java.util.Scanner;
public class UserPass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user; //Creating user-name variable.
String pass; //Creating password variable.
boolean isValidUser = false;
while(!isValidUser) {
System.out.println("Enter username here: "); //Message to tell user to input the user-name.
user = input.nextLine(); //Taking the users user-name input.
System.out.println("Enter the password here: "); //Message to tell user to input the password.
pass = input.nextLine(); //Taking the users password input.
//Validating the users User-name and password input.
if(user.equals("Shane") && (pass.equals("Temple"))) {
System.out.println("Correct!");
isValidUser = true;
}
else {
System.out.println("The Usernname or Password that you have entered was in-correct");
isValidUser = false;
}
}
}
}
Related
I'm building a login system in Java and I'm trying to mask the password input due to security measures but can't seem to find a way around it. This is what I'm Trying to do:
Username:
User1
Password:******
Here's my code to give you an idea
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Input = new Scanner (System.in);
System.out.println("Username:");
String Username = Input.nextLine();
System.out.println("Password:");
String Password = Input.nextLine();
}
}
Try readPassword() method of java
It doesn't mask a * but it hide the input we type to console
cnsl = System.console();
char[] pwd = cnsl.readPassword("Password: ");
System.out.println("Password is: "+pwd);
like this.......
You can use Console.readPassword() from https://docs.oracle.com/javase/7/docs/api/java/io/Console.html
This is my code so far that only works (displays the welcome message) when both a matching username and password have been entered.
I am unsure how to integrate a while loop that stops the user from progressing to the password stage if the usernameInput string does not match the username string, and loops over and over until the correct username has been entered. Then after I would like the same thing for the passwordInput string until it matches the password string. The idea is to have the program be able to loop over and over until the correct username AND password have been entered by the user.
[NOTE: I'm coming into java from a very basic knowledge of python, so everything may be a little disordered and inefficient]
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
String username,usernameInput, password, passwordInput;
username= "KenBoneL0ver";
password= "KenBone4Life";
Scanner myObj1= new Scanner(System.in);
System.out.println("Please enter your username:");
usernameInput= myObj1.nextLine();
if (!usernameInput.equals(username)) {
System.out.println("Incorrect username. Please try again:");
}
else {
System.out.println("Now please enter the correct password:");
}
Scanner myObj2= new Scanner(System.in);
passwordInput= myObj2.nextLine();
if (!passwordInput.equals(password)) {
System.out.println("Incorrect password. Please try again:");
}
else {
System.out.println("You have successfully logged in!");
}
myObj1.close();
myObj2.close();
}
}
Thanks for any help!
Can you please check if are you looking for something like this?
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
Scanner myObj1 = null;
try {
String username, usernameInput, password, passwordInput;
username = "KenBoneL0ver";
password = "KenBone4Life";
myObj1 = new Scanner(System.in);
while (true) {
System.out.println("Please enter your username:");
usernameInput = myObj1.nextLine();
if (!usernameInput.equals(username)) {
System.out.println("Incorrect username. Please try again:");
continue;
}
break;
}
while (true) {
// Scanner myObj2 = new Scanner(System.in);
System.out.println("Now please enter the correct password:");
passwordInput = myObj1.nextLine();
if (!passwordInput.equals(password)) {
System.out.println("Incorrect password. Please try again:");
continue;
} else {
System.out.println("You have successfully logged in!");
break;
}
}
// myObj2.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (myObj1 != null) {
myObj1.close();
}
}
}
}
Output:
Please enter your username:
test
Incorrect username. Please try again:
Please enter your username:
KenBoneL0ver
Now please enter the correct password:
test
Incorrect password. Please try again:
Now please enter the correct password:
KenBone4Life
You have successfully logged in!
You can use a while loop:
while (someBooleanCondition) {
statement(s);
}
When both conditions are true (password and username) then the boolean condition breaks the while loop and tells the user they have successfully logged in.
Here is a link that may be useful
You can use assignment operator when checking the condition inside while:
while (!username.equals(usernameInput = scan.nextLine())). Then you won't need any extra boolean variables and/or break/continue statements to implement necessary flow.
Aside comments related to the use of Scanner:
there's no need to create a separate instance to input username and password.
It's good to see that you cared for closing both Scanner instances. However, using try-with-resources construction guarantees that the resource implementing AutoCloseable interface will be closed automatically.
That being said, the code may be rewritten as follows:
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
String
username = "user",
password = "pswd",
usernameInput,
passwordInput;
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Please enter your username:");
while(!username.equals(usernameInput = scan.nextLine())) {
System.out.println("Incorrect username. Please try again:");
}
System.out.println("Now please enter the correct password:");
while(!password.equals(passwordInput = scan.nextLine())) {
System.out.println("Incorrect password. Please try again:");
}
System.out.println("You have successfully logged in!");
}
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I'm not sure how dumb I am or if I am missing something quite simple; anyhow, I am trying to get a basic username and password input from the user using the scanner utility.
I have made sure scanner was initialised correctly (Scanner sc = new Scanner(System.in)
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
The issue I am having is when I run this part of the code (above), the output I get looks like this (below) where I start inputting into the password section. Its as though it is just skipping over the first call to the scanner.
Username or Email:
Password: (this is where my input goes)
My only guess is that the scanner is taking the second printing as its input but I am not sure so any help is greatly appreciated.
p.s I will leave the entire method at the bottom incase it helps.
Thanks.
public static void loginPage() throws SQLException{
int requestCounter = 0;
do {
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
boolean validLoginRequest = accountLoginCheck(username, password);
if (validLoginRequest) {
break;
} else {
requestCounter++;
}
} while (requestCounter < 3);
if (requestCounter == 3) {
System.out.println("Too many attempts");
return;
}
System.out.print("TO MAIN MENU");
Remove \n from System.out.print("\nPassword: ");
Username or Email: myemail
Password: pass
Prompt: I am writing a Login program that asks the user for their username and password. All user info is stored in a password.txt file and passwords are stored as a hashcode. If the user enters an invalid username or a password that does not have the same hash as the hash in the entry, then the program should print “Unsuccessful login.” If the user enters a valid username and the password has the same hash as the hash in the entry, then the program should print “Login successful.“
The password.txt file is set up like so:
Real name:username:password_hash
Question: How do I search a .txt for a String and hashcode?
This is the code I have for now:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Scanner sf = new Scanner("passwords.txt");
String Username;
String Password;
System.out.println("Login ");
System.out.println("Please Enter Username: ");
Username = sc.next();
System.out.println("Please Enter Password: ");
Password = sc.next();
String login = Username + ":" + Password.hashCode();
System.out.println(login);
while(sf.hasNextLine()){
if((login.equals(sf.nextLine().trim()))){
System.out.println("Login Successful!");
break;
}
if(!(login.equals(sf.nextLine().trim()))){
System.out.println("Login Unsuccessful!");
}
}
I'm trying to search the code for a String that looks like username:hashcodePassword
Problems: The code doesn't print either if statement and gives me this error when running the program
Error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at LoginApplication.main(LoginApplication.java:29)
Simple explaination: your code checks if the file has a next line, so it check the first nested if but here it reads a line from the file and the pointer to the file is moved to the next line. Then it checks the next if statement and here another line of your file is read.
The problem appears because you are actually reading two lines of file at one time.
The solution is
while(sf.hasNextLine()) {
final String currentLine = sf.nextLine().trim();
if(login.equals(currentLine)){
System.out.println("Login Successful!");
break;
} else {
System.out.println("Login Unsuccessful!");
}
}
then if you need to have more if statements you can use the currentLine variable instead of reading another line of file.
I know this might seem like a simple/silly question, but I am trying to keep my code as organized and simple as possible. The problem that I am having is with a while loop for validation. I am validating a string input. I am using the validation simply to make sure that something is entered. The only time I would like the while loop to run is when no information is entered at all, so I would like to include every character and symbol. The question that I have, is that I am wondering if there is a shorter way to include every character possible except for simply hitting enter of course. Here is the simple code snippet.
Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");
System.out.print("Please enter your name: ");
String email = input.nextLine();
while(!email.matches("[a-zA-Z]+"));
{
System.out.println("\nPlease enter a valid E-Mail.");
email = input.nextLine();
}
out.println("E-Mail: " + email);
What about restructuring it as a do-while and only having one print/scan?
Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");
String email;
String prompt = "Please enter your name: ";
do {
System.out.print(prompt);
email = input.nextLine();
prompt = "\nPlease enter a valid E-Mail.\n"
} while (!email.matches("[a-zA-Z]+"));
out.println("E-Mail: " + email);