Java 密码提示和从if语句调用方法
这是我第一次尝试问一个问题,希望它能正确地表现出来。基本上,我需要的程序做的是要求用户预设的帐号和密码,只允许他们3次尝试。然后,当两个要求都满足时,我想调用另一个方法,这样我就可以继续程序了。我遇到的第一个问题是,当我输入正确的密码时,它仍然显示为不正确,我不知道为什么,然后我想知道是否在if语句中正确调用了该方法。谢谢Java 密码提示和从if语句调用方法,java,methods,Java,Methods,这是我第一次尝试问一个问题,希望它能正确地表现出来。基本上,我需要的程序做的是要求用户预设的帐号和密码,只允许他们3次尝试。然后,当两个要求都满足时,我想调用另一个方法,这样我就可以继续程序了。我遇到的第一个问题是,当我输入正确的密码时,它仍然显示为不正确,我不知道为什么,然后我想知道是否在if语句中正确调用了该方法。谢谢 import java.util.Scanner; public class Part4 { public static void main(String[] args
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");
}
}
}
import java.util.Scanner;
公共课第四部分{
公共静态void main(字符串[]args)
{
字符串password=“password”,passwordtrunt=null;
int accnum=123456789,actry=0,trys=0;
扫描仪输入=新扫描仪(System.in);
while(actry!=accnum){
System.out.println(“\n请输入您的帐号”);
acctry=input.nextInt();
if(actry!=accnum)
System.out.print(“该号码不正确,请重试”);
其他的
if(actry==accnum)
{
while(尝试<3次)
{
System.out.println(“\n请输入密码”);
passwordtrunt=input.next();
如果(密码尝试!=密码){
系统输出打印(“该密码不正确”);
尝试++;
}
其他的
如果(密码尝试==密码){
系统输出打印(“正确”);
AccountDetails.Details(args);
}
}
System.out.print(“\n您已超过尝试次数”);
}
}
}
公共静态类AccountDetails{
私有静态无效详细信息(字符串[]args){
系统输出打印(“它工作”);
}
}
}
有两个问题
- 1:您正在执行while循环,不管它是否成功
在Java语言中,字符串是对象,因此使用“==”对它们进行比较是通过引用进行测试,而不是通过相等性进行测试 我相信你要找的是
if (passwordattempt.equals(password)) {
查看此处了解更多信息:
请学习如何比较字符串。正如SLaks所说的补充,请阅读对象引用相等与我们认为相等的内容。
while(tries < 3 && !successfulPassword)
if(passwordAttempt.equals(password) {
successfulPassword = true;
} else {
tries++;
}
if (passwordattempt.equals(password)) {