gpt4 book ai didi

java - 学习Java,For循环不渲染

转载 作者:行者123 更新时间:2023-12-02 08:41:24 24 4
gpt4 key购买 nike

我在下面创建了这个PassworField方法。目的是如果用户输入正确的密码 hello 则跳出循环。在阻止用户之前,它应该循环 5 次。如果用户第一次输入正确的密码,它确实会爆发,但如果用户第一次输入错误的密码,然后在第二次尝试时更正,则不会爆发。即使我输入正确的密码,它也只会循环 5 次然后阻止。如果您能帮忙,我将不胜感激......让我发疯......

public class LoginPage {


static String password = "hello";
static Scanner scn = new Scanner(System.in);
static String input = scn.nextLine();


public static void PasswordField() {
System.out.println("Enter the password");
for (int i = 0; i <5; i++) {
if (password.equals(input)) {
System.out.println("You are In");
break;
}
else if(!input.equals(password)) {
System.out.println("Wrong, Please Enter the Password again:");
scn.nextLine();
}
else {
System.out.println("You are Blocked sucker. call helpdesk");
}


}
scn.close();
}

最佳答案

一旦循环终止,您需要检查用户是否超出了允许的最大尝试次数。

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
inputPassword();
}

public static void inputPassword() {
final Scanner scn = new Scanner(System.in);
final String password = "hello";
String input;
int i;
for (i = 1; i <= 5; i++) {
System.out.print("Enter the password: ");
input = scn.nextLine();
if (password.equals(input)) {
System.out.println("You are In");
break;
} else if (i < 5) {
System.out.println("Wrong, Please Enter the Password again.");
}
}
if (i > 5) {
System.out.println("You are blocked as you have exceeded the maximum limit.");
}
}
}

示例运行:

Enter the password: 1
Wrong, Please Enter the Password again.
Enter the password: 2
Wrong, Please Enter the Password again.
Enter the password: 3
Wrong, Please Enter the Password again.
Enter the password: 4
Wrong, Please Enter the Password again.
Enter the password: 5
You are blocked as you have exceeded the maximum limit.

另一个示例运行:

Enter the password: 1
Wrong, Please Enter the Password again.
Enter the password: Hello
Wrong, Please Enter the Password again.
Enter the password: hello
You are In

其他一些重要说明:

  1. 请勿关闭 System.inScanner,因为它也会关闭 System.in
  2. 关注Java naming conventions例如根据命名约定,该方法 PasswordField 应命名为 passwordField

关于java - 学习Java,For循环不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61371435/

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