我一直在尝试让下面的代码在不使用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;
}
}
}
}
这是我尝试使用 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)));
}
}
我哪里出错了?
最佳答案
您可以这样做,或者不要在 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);
}
}
关于java - 创建java代码提示用户输入密码并只允许尝试3次然后退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34721351/