简体   繁体   中英

While loop using Scanner

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

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.

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM