Reputation:
Hi I am writing a program that uses Scanner to get input from a user and then uses a boolean method to check if the input is up to six characters in length. The problem is that, I used a while loop to keep asking for input if the length is less than six; but after the first wrong input, if you insert a string of six letters or longer, the loop still continues. Please here is the program:
import java.util.Scanner;
public class PasswordChecker{
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String input;
System.out.println("Enter a password");
input = kbd.nextLine();
boolean result = LengthCheck(input);
LengthCheck(input);
while(result == false){
System.out.println("Please enter a minimum password of six characters");
input = kbd.nextLine();
}
System.out.println(input);
System.out.println(result);
}//close main
public static boolean LengthCheck(String input){
boolean result = false;
int length = 6;
if(input.length() >= length){
result = true;
}
return result;
}//LengthCheck
}//PasswordChecker
Thanks
Upvotes: 0
Views: 1820
Reputation: 12042
you need to check LengthCheck()
inside the while loop ,try this
while(result == false){
System.out.println("Please enter a minimum password of six characters");
input = kbd.nextLine();
-> result = LengthCheck(input);
}
Upvotes: 0
Reputation: 3281
In you scenario, you want to exit the loop when the password is more than six characters long. Thus you need to make sure you are checking that condition in your while
statement.
This will do the trick for you:
while(LengthCheck(input) == false){
System.out.println("Please enter a minimum password of six characters");
input = kbd.nextLine();
}
The loop will continue to go-around until LengthCheck
is satisfied you've entered a password of 6 digits.
Upvotes: 1