我需要创建一个密码检查器

时间:2017-02-14 06:27:14

标签: java

我需要初始化密码。密码不等于密码,小于3的密码不断询问用户密码。如果密码不正确,则授予密码正确的打印访问权限。

import java.util.Scanner;

public class PasswordChecker {
  public static void main (String [] args) {

   Scanner in = new Scanner(System.in);

    String secretPassword = "alejandra";
    String password;
    int attempts = 3;

      System.out.println("Please enter password");
       password = in.nextLine ();


      while (!password.equals(secretPassword) && attempts<3) 
    System.out.println ("incorrect try again");
      password = in.nextLine ();
      if (password.equals (secretPassword)
       System.out.println ("access granted");
  }
}

3 个答案:

答案 0 :(得分:3)

试试这个

  • 更改为do while
  • 添加大括号
  • 设置尝试更正值
  • )添加到if
  • 增加attempts计数器

    Scanner in = new Scanner(System.in);
    
    String secretPassword = "alejandra";
    String password;
    int attempts = 1;
    
    do {
      System.out.println("Please enter password");
       password = in.nextLine ();
       if (password.equals (secretPassword)) {
           System.out.println ("access granted");
           break;
       }
       if (attempts < 3)
           System.out.println ("incorrect try again");
       else 
           System.out.println ("failed");       
    }
    while (attempts++ < 3); 
    

或者如果您想要while循环解决方案

    Scanner in = new Scanner(System.in);

    String secretPassword = "alejandra";
    String password;
    int attempts = 0;

    while (attempts++ < 3) {
      System.out.println("Please enter password");
       password = in.nextLine ();
       if (password.equals (secretPassword)) {
           System.out.println ("access granted");
           break;
       }
       if (attempts < 3)
           System.out.println ("incorrect try again");
       else 
           System.out.println ("failed");
    }

答案 1 :(得分:0)

玩得开心。

如果您强调计数器,最好使用forloop而不是while循环,因为它会导致多次尝试。

    public static void main (String [] args) {

   Scanner in = new Scanner(System.in);

    String secretPassword = "alejandra";
    String password;
    int attempts = 3;

      System.out.println("Please enter password");
       password = in.nextLine ();


     for(int i=1;i<=attempts;i++){
    System.out.println ("Incorrect try again");
      password = in.nextLine ();
      if (password.equalsIgnoreCase(secretPassword)){
       System.out.println ("access granted");
  }
     }
}

答案 2 :(得分:0)

您有一个无限循环,因为您没有更改attempts变量。

从while循环外部删除password变量并提示,并将while循环更改为:

while(attempts > 0) {
    System.out.print("Enter password: ");
    if(in.nextLine().toLowerCase().equals(secretPassword)) {
        System.out.println("access granted.");
        break;
    }
    else {
        System.out.println("Incorrect. Try again.");
        attempts -= 1;
    }
}