Newbie, why is my program printing output twice?
hey guys, recently opened a java book and started coding, it was fun
having problem with this password checker that i tried my hand at
it prints output twice
Code :
import java.util.*;
public class SimplePassword {
public static void main(String[] args) {
//variables
Scanner myScanner = new Scanner(System.in);
String password = "swordfish";
String userinput;
//runs once and then repeatedly while the password check returns false
do{
System.out.println("Write password ");
userinput = myScanner.next();
checkPW(password, userinput);
}while(checkPW(password, userinput) == false);
} //end main
//comparison method
public static boolean checkPW(String password, String userinput){
if(password.equals(userinput)){
System.out.println("Access granted");
return true;
}
else
{
System.out.println("Access denied.");
return false;
}
} //end checkPW
}// end class
example output:
Code :
Write password
monkeys
Access denied.
Access denied.
Write password
swordfish
Access granted
Access granted
Can you explain why it does this to me please? :)
Re: Newbie, why is my program printing output twice?
How many times are you call the checkPW method in your loop? Twice! Once inside of the loop itself, and once in the while boolean condition. I suggest you call it only once.
Re: Newbie, why is my program printing output twice?
Thank you very much! Changed the while to this:
Code :
while(!userinput.equals(password));
now it works just fine :3
Re: Newbie, why is my program printing output twice?
Great, glad you've got it to work!