I'm working on a project in Java that is kind of like a digital time-machine, it basically saves what happened on a specific sate, archives it to a specific file, and stores it in a directory somewhere for safe keeping. Right now I'm working on a password function. I have the basics down for checking if it's right or wrong, but when I input the wrong answer, the class ends after saying "Invalid Password".
Is there a way to have it loop from the end of else statement to the beginning of main so I don't have to re-execute the class everytime?
import java.util.Scanner;
import java.util.*;
public class Adam {
public static void main(String args[]) {
String passwrd = "password";
String inputPassword;
System.out.print("Please Input Password ");
Scanner sc = new Scanner(System.in);
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
} else {
System.out.println("Invalid Password");
}
}
}
You can use a do while loop, if user input is invalid then continue the loop else not.
import java.util.Scanner;
import java.util.*;
public class Adam {
public static void main(String args[]) {
String passwrd = "password";
String inputPassword;
boolean b = true;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Please Input Password ");
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
b = false;
} else {
System.out.println("Invalid Password");
b = true;
}
} while (b);
}
}
DEMO
Whenever you want to run some code, check the result and then repeat if necessary the most obvious structure is do while.
Something like the following:
String inputPassword = null;
do {
if (inputPassword != null)
System.out.println("Invalid password");
System.out.println("Enter password");
inputPassword = sc.nextLine();
} while (!inputPassword.equals(password));
public static void main(String args[]) {
String password = "password";
String inputPassword;
while(inputPassword == null || !inputPassword.equals(password)){
System.out.print("Please Input Password ");
Scanner sc = new Scanner(System.in);
inputPassword = sc.nextLine();
if (!inputPassword.equals(password)) {
System.out.println("Invalid Password");
}
}
System.out.println("Password Accepted, Loading Archive...");
}
It's a good idea to have a limited number of tries to input the password. For example to have three tries to enter password, you'd have this code:
Scanner sc = new Scanner(System.in);
for (i = 0; i < 4; ++i) {
System.out.print("Please Input Password ");
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
break;
}
else {
System.out.println("Invalid Password");
}
}
Just put whole code into while(true) loop which you will break if password is walid
public static void main(String args[])
{
String passwrd = "password";
String inputPassword;
while(true)
{
System.out.print("Please Input Password ");
Scanner sc = new Scanner(System.in);
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd))
{
System.out.println("Password Accepted, Loading Archive...");
break; //here you are getting out of loop
}
else
{
System.out.println("Invalid Password");
//you are not breaking loop so the program will return to the beggining
}
}
}
I have added one while loop and one flag in your program. Please have a look:
public static void main(String[] args) {
String passwrd = "password";
boolean wrongPassword = true;
while(wrongPassword){
String inputPassword;
System.out.print("Please Input Password ");
Scanner sc = new Scanner(System.in);
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
wrongPassword = false;
}
else {
System.out.println("Invalid Password");
}
}
}
use a do-while loop :
String passwrd = "password";
String inputPassword ="";
Scanner sc = new Scanner(System.in);
do{
System.out.print("Please Input Password ");
// get the password from user
inputPassword = sc.nextLine();
// if password matches print success and break out of loop
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
break;
}
else{
System.out.println("Invalid Password");
}
}while(true);
Use a do-while loop. Also, your code has some security issues:
Don't use System.in for passwords. Use Console instead. (However, if you run the program from an IDE, you may not have a Console. In that case, use a GUI method instead.)
Hash your password straight after you input it.
Clear your password buffer as soon as possible after input (i.e. overwrite it). See Console documentation.
Console con = System.console();
if (con == null)
throw new IOException("This JVM has no console");
boolean pwdCorrect;
do {
char[] inputPassword = con.readPassword("Please input password: ");
String hashedInputPassword = hashPassword(inputPassword); // search Internet for how to hash a password
for (int i = 0; i < inputPassword.length; i++)
inputPassword[i] = '\0';
pwdCorrect = isValidPassword(hashedInputPassword); // e.g. by looking it up in a password file
if (pwdCorrect)
System.out.println("Password accepted. Loading archive...");
else
System.out.println("Invalid password.");
} while (!pwdCorrect);
Related
I'm practicing if and else statements and i did a guess your password string, if you input the right password a congratulation message appears but if you enter the wrong one another message appears that says "Please try again" the issue that im having is that i dont know how to set another congratulation message if the user guess the right password on try again.
public static void main(String[] args) {
String password = "Shippuden345";
System.out.println("Enter or guess the password: ");
Scanner scanner = new Scanner(System.in);
String guess = scanner.nextLine();
System.out.println(password.equals(guess));
if (password.equals(guess)) {
System.out.println("Your guess was correct");
return;
}
else;
{
System.out.println("Please try again: ");
Scanner scanner1 = new Scanner(System.in);
String again = scanner1.nextLine();
}
}
}
i want to set another message in here, if the user guess the password correctly after trying again.
else;
{
System.out.println("Please try again: ");
Scanner scanner1 = new Scanner(System.in);
String again = scanner1.nextLine();
}
}
}
It would be best if you used a do while loop:
public static void main(String[] args) {
String password = "Shippuden345";
String guess;
do{
System.out.println("Enter or guess the password: ");
guess = scanner.nextLine();
System.out.println(password.equals(guess));
if (password.equals(guess)) {
System.out.println("Your guess was correct");
return;
}
else {
System.out.println("Please try again: ");
}
}while(!password.equals(guess));
}
I have edited your code. However, I have added it to a static void:
I have also added an int to be shown if the first attempt was incorrect. Hope you like it.
class s{
public static void check(){
int attempts = 0;
String password = "Shippuden345";
System.out.println("Enter or guess the password: ");
Scanner scanner = new Scanner(System.in);
String guess = scanner.nextLine();
System.out.println(password.equals(guess));
while(attempts < 5){
if (password.equals(guess) && attempts == 0) {
System.out.println("Your guess was correct");
return;
}
else
if (password.equals(guess) && attempts > 0) {
System.out.println("Attempt number "+attempts+" was correct.");
return;
}
else{
System.out.println("Please try again: ");
attempts++;
guess = scanner.nextLine();
}
}
}
public static void main(String[] args) {
check();
}
}```
You can put the input and processing of the input value inside an infinite loop (e.g. while(true){}) which you can break on the correct input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String password = "Shippuden345";
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter or guess the password: ");
String guess = scanner.nextLine();
if (password.equals(guess)) {
System.out.println("Your guess was correct");
break;
} else {
System.out.println("Please try again: ");
}
}
}
}
A sample run:
Enter or guess the password: aSD
Please try again:
Enter or guess the password: 12H
Please try again:
Enter or guess the password: Shippuden345
Your guess was correct
You can use a loop that starts after the first guess of passwords if the guess is incorrect and continues the loop if passwords entered in the following trials are incorrect.
Then breaks the loop when the password matches and prints the congratulate message.
The loop do-while is a loop that should run at least once and then logging all output of the code from inside that { }. The case of do-while for me is not a valid input and would not run the actual input and would output NULL.
import java.util.Scanner;
import static java.lang.System.*;
class PasswordCheck
{
public String password;
public String ag;
public void PasswordCheck()
{
do {
password = ag;
if(password == "1234") {
System.out.println("success");
}else {
System.out.println("FAIL" + password);
PasswordCheck d = new PasswordCheck();
d.check();
}
} while (password != "1234");
if(password == "1234") {
System.out.println("success");
}
}
public void check()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the password:");
String ag = keyboard.next();
System.out.println(ag);
PasswordCheck as = new PasswordCheck();
as.PasswordCheck();
}
}
public class PassRunner
{
public static void main( String args[] )
{
PasswordCheck test = new PasswordCheck();
test.check();
}
}
I have already tried re putting the type of class and also putting password = ag;
Output:
Enter the password:1234
1234
FAILnull
Enter the password:1234
1234
FAILnull
Enter the password:
You're assigning ag to password. Both of them are not initialized, thus having default value null. You should have your password initialized with some value before if statement.
public void check()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the password:");
String ag = keyboard.next();
System.out.println(ag);
PasswordCheck as = new PasswordCheck();
as.PasswordCheck();
}
It's because in above, the block is not using ag as an instance variable, instead you are declaring it as a local variable. Change
`String ag = keyboard.next();
this, to this;
ag = keyboard.next();
`
I made a program that check a string if there is at least one vowel in the string. But when I input a string that have a vowel in it, the result is ""your password word is not acceptable" instead of "your password word is acceptable".
can someone show me where I do wrong? thank you!
here is the program:
import java.util.Scanner;
public class checker {
static Scanner input= new Scanner(System.in);
public static void main(String[] args) {
String password;
System.out.println("enter your password:");
password= input.next();
String vowel[]= {"a","e","i","o","u"};
for(int i=0; i<5;i++) {
boolean check[] = new boolean[5];
check[i]=password.contains(vowel[i]);
if(i==vowel.length-1&&check[0] ==false && check[1]==false && check[2]==false && check[3]==false && check[4]==false) {
System.out.println("your password word is not acceptable");
}else System.out.println("your password is acceptable");
}
}
}
You can do this in the following way:
import java.util.Scanner;
public class checker {
static Scanner input= new Scanner(System.in);
public static void main(String[] args) {
String password;
System.out.println("enter your password:");
password= input.next();
String vowel[]= {"a","e","i","o","u"};
boolean check = false;
for(int i=0; i<5;i++) {
check = password.toLowercase().contains(vowel[i]);
if(check){
break;
}
}
if(!check){
System.out.println("your password word is not acceptable");
}else {
System.out.println("your password is acceptable");
}
}
}
You can easily check if a string contains vowel or not using regular expression.Please check the below code:
public static void main(String[] args) {
String input = "tssta";
String regex= ".*[AEIOUaeiou].*";
if(input.matches(regex)){
System.out.println("your password word is acceptable");
}else {
System.out.println("your password word is not acceptable");
}
}
I've a problem with my while loop.
It works fine if the while loop conditions is false(when the password is wrong), but when the password is right it writes both You are logged in and Wrong password.
I understand why it does so but I don't understand how to solve the problem. I need to use a while loop because it's a school assignment that requires it.
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(scan.equals(rightPassword)){
System.out.println("You are logged in");
break;
}
System.out.println("Wrong password");
}
}
What you should have done is :
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
String scan="";
while(true){
System.out.println("Write your password: ");
scan = scanner.nextLine();
if(scan.equals(rightPassword)) {
System.out.println("You are logged in");
break;
} else {
System.out.println("Wrong password");
}
}
}
}
In this what we do is we have an endless for loop which will not break until you supply the right password. You can add some kin of number of tries to this as a breaking condition too.
Based on the comment I know, it become a infinite loop and that's why i use break. My requirement is that i must use a While loop. I know how to use a if-loop to solve the problem. Your solution should look like :
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
while(!rightPassword.equals(scanner.nextLine())) {
System.out.println("Wrong password");
System.out.println("Write your password: ");
}
System.out.println("You are logged in");
}
}
You can use below code.
int a=1;
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(scan.equals(rightPassword)){
System.out.println("You are logged in");
a=0;
break;
}
if(a==1){
System.out.println("Wrong password");
}
without changing your code this will help you.
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(scan.equals(rightPassword)){
System.out.println("You are logged in");
break end;
}
System.out.println("Wrong password");
end:
}
}
You may have a couple of things backwards. Check for a wrong password, not a right one in the loop, and ask for their password again. This way you will receive one message from the system and that's a bad password, or a good one once they 'successfully log in'.
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(!scan.equals(rightPassword)){
System.out.println("Wrong password. Please try again");
System.out.println("Write your password: ");
String scan = scanner.nextLine();
}
System.out.println("You are logged in");
}
}
I just started to learn Java a few days ago and i wanted to create a program that will create an account,stored it and then if we enter the exact username and password then it will say "login successful".Please don't mind my way of naming the variables and classes.My question is in my "crttacc" class,where i have set up 2 get method to get the un and pa variables.However,in my main method after running the create method in crttacc,the input data seem to gone away and not stored in the un,pa variables as when i try to print them out to check it,it would return "null".I'm a newbie so i'm not quite sure that my question was clear enough and i hope that u guys can help me.You have my gratitude.
Here's my codes:(please don't laugh :D)
import java.util.Scanner;
class crttacc {
String pa;
String un;
void create() {
Scanner unin = new Scanner(System.in);
Scanner passin = new Scanner(System.in);
System.out.println("enter the user name: ");
String l1 = unin.nextLine();
System.out.println("enter the password: ");
String l2 = passin.nextLine();
l1=un;
l2=pa;
}
String getpass(){
return un;
}
String getuser(){
return pa;
}
}
class loginn {
;
void logingin() {
crttacc acc1 = new crttacc();
String pass = acc1.getpass();
String user = acc1.getuser();
System.out.println(pass);
System.out.println(user);
Scanner passwordinput = new Scanner(System.in);
Scanner usernameinput = new Scanner(System.in);
System.out.println("username:");
String line1 = usernameinput.nextLine();
System.out.println("Password:");
String line2 = passwordinput.nextLine();
String d1=line1;
String d2=line2;
if(d1.equals(pass) && d2.equals(user)) {
System.out.println("login successfull");
}
else {
System.out.println("try again");
}
}
}
public class login3 {
public static void main(String[] args) {
Scanner com = new Scanner(System.in);
System.out.println("enter your command: create account or login");
String com1 = com.nextLine();
String l1=com1;
if(com1.equals("create account")) {
crttacc acc1 = new crttacc();
acc1.create();
}
Scanner com2 = new Scanner(System.in);
System.out.println("would you like to login now? y/n");
String cm2 = com2.nextLine();
String l2=cm2;
if(l2.equals("y")) {
loginn log1 = new loginn();
log1.logingin();
}
else{
}
}
}
it's :
un=l1;
pa=l2;
in the Create() method
The problem seems to be, that you store the input data you get through the scanner in l1 and l2. Then you give your l1 and l2 variables the value of un and pa (which is null at this point). At the end of your method the local variables l1 and l2 are thrown away and nothing changed for your un and pa.
You propably wanted something like this:
void create() {
Scanner scanner = new Scanner(System.in);
System.out.println("enter the user name: ");
String l1 = scanner.nextLine();
System.out.println("enter the password: ");
String l2 = scanner.nextLine();
this.un = l1;
this.pa = l2;
}
With this you stored the values of l1 and l2 in your fields un and pa and can access them through your getters.
Hint: you don't need a new Scanner for every input. You can reuse it :)