学习Java和For循环不是渲染

  • 本文关键字:循环 Java For 学习 java
  • 更新时间 :
  • 英文 :


我在下面创建了这个PassworField方法。意图是如果用户输入正确的密码CCD_ 2。在阻止用户之前,它应该循环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.in关闭Scanner,因为它也会关闭System.in
  2. 遵循Java命名约定,例如方法,根据命名约定,PasswordField应命名为passwordField

缺少的是用新值更新input。此外,在for循环结束后,被阻止的逻辑应该是

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");
scn.close();
return;
} else {
System.out.println("Wrong, Please Enter the Password again:");
input = scn.nextLine();
}
}
System.out.println("You are Blocked sucker. call helpdesk");
scn.close();
}

最新更新