0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@user2932716 Glad to help - You can remove any other calls to LengthCheck there were two above the loop in your example code above, these are not required.
0

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);

    }

Comments