gpt4 book ai didi

java - 密码提示并从 if 语句调用方法

转载 作者:行者123 更新时间:2023-11-30 04:07:12 24 4
gpt4 key购买 nike

这是我第一次尝试提出问题,希望它能正确显示。基本上我需要程序做的是询问用户预设的帐号和密码,并且只允许他们尝试 3 次。然后,当这两个要求都满足时,我想调用另一种方法,以便我可以继续该程序。我遇到的第一个问题是,当我输入正确的密码时,它仍然显示为不正确,我不知道为什么,然后我想知道我是否正确调用了 if 语句中的方法。谢谢。

import java.util.Scanner;


public class Part4 {

public static void main(String[] args)
{

String password = "password", passwordattempt = null;
int accnum = 123456789, acctry = 0, tries = 0;
Scanner input = new Scanner (System.in);


while (acctry != accnum){
System.out.println("\nPlease enter your account number");
acctry = input.nextInt();

if (acctry != accnum)
System.out.print("That number is incorrect. Please try again.");

else
if (acctry == accnum)
{


while (tries < 3)
{


System.out.println("\nPlease enter password");
passwordattempt = input.next();


if (passwordattempt != password){
System.out.print("That password is incorrect");
tries++;
}
else
if (passwordattempt == password){
System.out.print("That is correct");
AccountDetails.Details(args);
}
}

System.out.print("\nYou have exceeded the ammount of tries");

}


}

}

public static class AccountDetails {
private static void Details(String[] args){
System.out.print("it works");
}
}

}

最佳答案

两个问题。

  • 1:无论成功与否,您都在执行 while 循环。

.

while(tries < 3)

应该是

while(tries < 3 && !successfulPassword)

您需要添加 successPassword 变量,这样您就不会第一次就正确,但仍然需要输入密码。

  • 2:你对字符串的比较是严重错误的。有两件事引起了我的注意。首先,您无法使用 ==!= 获得您期望的结果。您必须使用.equals()。其次,你不需要像对待人类那样重复相反的子句。例如,我告诉我的女儿“如果你吃晚饭,那么你可能有 cookies 。否则,如果你不吃晚饭,那么你可能没有 cookies 。”对于计算机来说,你不需要最后“如果你不吃晚饭”。它肯定是正确的(因为无论如何你都在 else block 中)并且它只是把它弄乱了。这样就变成了

.

if(passwordAttempt.equals(password) {
successfulPassword = true;
} else {
tries++;
}

关于java - 密码提示并从 if 语句调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20477811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com