java 创建java代码以提示用户输入密码并只允许3次尝试然后退出程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34721351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:14:07  来源:igfitidea点击:

Creating java code to prompt user for password and allow only 3 attempts then quit the programme

java

提问by Mondo192

I have been experimenting with trying to get the code below running WITHOUT using a break statement (but i can't figure it out)

我一直在尝试使用 break 语句让下面的代码在不运行的情况下运行(但我无法弄清楚)

import java.io.*;
import java.util.*;

public class Password
{
    public static void main (String [] args)
    {
        final String PASSWORD = "Test";

        for (int passAttempts = 0; passAttempts < 3; passAttempts++) 
        {
            System.out.print("\nEnter Your Password: ");
            Scanner input = new Scanner(System.in);
            String inputPass = input.nextLine();

            if (!(inputPass.equals(PASSWORD))) 
            {
                System.out.println("\nWrong Password Try Again");
            } 
            else 
            {
                System.out.println("\nWelcome!");
                break;
            }
        }
    }
}

This is my alternative attempt of trying to use a switch statement to "catch" each iteration of the loop and perform an action, but I'm not sure why its endless loop:

这是我尝试使用 switch 语句“捕获”循环的每次迭代并执行操作的另一种尝试,但我不确定为什么它会无限循环:

import java.io.*;
import java.util.*;

public class Password2
{
    public static void main (String [] args)
    {
        final String PASSWORD = "Test";

        System.out.print("\nEnter Your Password: ");
        Scanner input = new Scanner(System.in);
        String inputPass = input.nextLine();

        do
        {
            for(int passAttempts = 0; passAttempts < 3; passAttempts++)
            {
                switch(passAttempts)
                {
                    case 0:
                        System.out.println("\nWrong password try again\t2 attempts remaining");
                        break;
                    case 1:
                        System.out.println("\nWrong password try again\t1 attempts remaining");
                        break;
                    case 2:
                        System.out.println("\nWrong password try again\t0 attempts remaining");
                        break;
                    default:
                        System.out.println("\nContact Help desk");
                        break;
                }  
            }    
        }
        while(!(inputPass.equals(PASSWORD)));
    }
}

Where am I going wrong?

我哪里错了?

回答by user3284549

You can do it like this, alternatively instead of comparing password in while statement put a break statement below the if(password.equals(PASSWORD), but since you said you want to avoid it:

您可以这样做,或者,不要在 while 语句中比较密码,而是在 if(password.equals(PASSWORD) 下方放置一个 break 语句,但既然您说要避免它:

public static void main(String[] args) 
{
    final String PASSWORD = "Test";
    Scanner sc = new Scanner(System.in);
    int attempts = 3;
    String password = "";
    while (attempts-- > 0 && !PASSWORD.equals(password)) //compares and then decrements
    {
        System.out.print("Enter your password: ");
        password = sc.nextLine();
        if (password.equals(PASSWORD)) 
            System.out.println("Welcome");
        else 
            System.out.println("Incorrect. Number of attempts remaining: " + attempts);        
    }
}

回答by Thiago

Using flag without change your code:

在不更改代码的情况下使用标志:

import java.util.*;

public class Password {
    public static void main(String[] args) {
        final String PASSWORD = "Test";
        boolean wrongPass = true;

        for (int passAttempts = 0; passAttempts < 3 && wrongPass; passAttempts++) {
            System.out.print("\nEnter Your Password: ");
            Scanner input = new Scanner(System.in);
            String inputPass = input.nextLine();

            if (!(inputPass.equals(PASSWORD))) {
                System.out.println("\nWrong Password Try Again");
            } else {
                System.out.println("\nWelcome!");
                wrongPass = false;
            }
        }
    }
}

Ps: close your Scanner ;)

Ps:关闭您的扫描仪;)

回答by Mondo192

I ended up with the following code in the end after some experimentation. The reasoning behind the programme...does the programme quit because the initialised boolean value of false is changed to true? Or is it because of the value changing in the for loop? Its works but its a bit tricky to explain why it functions hmm...

经过一些实验,我最终得到了以下代码。程序背后的推理...程序是否因为 false 的初始化布尔值更改为 true 而退出?还是因为for循环中的值发生了变化?它的工作原理,但解释它为什么起作用有点棘手,嗯......

The for loop to my understanding behaves like so;

根据我的理解,for 循环的行为是这样的;

  • is 1 <= 3? Yes, so its True...and NOT false = TRUE
  • is 2 <= 3? Yes, so its True...and NOT false = TRUE
  • is 3 <= 3? Yes, so its True...and NOT false = TRUE
  • is 4 <= 3? No, so its false...and NOT false = false -> breaks loop
  • 是 1 <= 3?是的,所以它是真的......而不是假的 = TRUE
  • 是 2 <= 3?是的,所以它是真的......而不是假的 = TRUE
  • 是 3 <= 3?是的,所以它是真的......而不是假的 = TRUE
  • 是 4 <= 3?不,所以它是假的……而不是假的 = 假 -> 中断循环

The part I'm confused on is declaring the boolean value as TRUE when the right password is entered, I don't grasp why it quits the programme...

我感到困惑的部分是在输入正确的密码时将布尔值声明为 TRUE,我不明白为什么它会退出程序......

Can someone clarify this for me with an equation perhaps? Many thanks.

有人可以用一个方程式为我澄清这一点吗?非常感谢。

final String PASSWORD = "Test"; //sets constant password 
final int MAX_PASS_ATTEMPTS = 3; //sets constant attempts
boolean adminLoggedIn = false;

    for(int passAttempts = 1; passAttempts <= MAX_PASS_ATTEMPTS && !adminLoggedIn; passAttempts++) //compares and increments passAttempts
    {
        System.out.print("\nPassword: ");
        Scanner input = new Scanner(System.in);
        String inputPass = input.nextLine();

            if (!(inputPass.equals(PASSWORD))) //If "Cisco" is not entered as password
            {
                System.out.println("\nERROR! Wrong Password! \t" + ((passAttempts - MAX_PASS_ATTEMPTS)*(-1)) + " Attempts Remaining"); //Deducts amount of attempts remaining
            } 
            else 
            {
                System.out.println("\nWelcome!");
                adminLoggedIn = true; //breaks loop 
            } 
}

回答by Carlos Ferreira

Just use a while and some flags:

只需使用一段时间和一些标志:

final String PASSWORD = "Test";
    final int MAX_PASS_ATTEMPS = 3;
    boolean isLoggedIn = false;
    int passAttemps = 0;
    while (passAttemps < MAX_PASS_ATTEMPS && !isLoggedIn) {
        System.out.print("\nEnter Your Password: ");
        Scanner input = new Scanner(System.in);
        String inputPass = input.nextLine();

        if (!(inputPass.equals(PASSWORD))) {
        System.out.println("\nWrong Password Try Again");
        passAttemps++;
        } else {
        System.out.println("\nWelcome!");
        isLoggedIn =true;
        break;
        }
    }