java 输入三次密码
时间: 2023-11-24 11:43:10 浏览: 34
以下是 Java 代码示例,演示如何输入三次密码:
```java
import java.util.Scanner;
public class PasswordInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int attempts = 3;
String password = "password123";
while (attempts > 0) {
System.out.print("Please enter the password: ");
String input = scanner.nextLine();
if (input.equals(password)) {
System.out.println("Password correct. Access granted.");
break;
} else {
System.out.println("Password incorrect. Attempts left: " + (--attempts));
}
}
if (attempts == 0) {
System.out.println("Access denied. Too many attempts.");
}
scanner.close();
}
}
```
在此示例中,我们首先创建一个 `Scanner` 对象,用于读取用户输入。然后,我们定义了一个变量 `attempts`,该变量存储可以尝试输入密码的次数。我们还定义了一个字符串变量 `password`,其中包含正确的密码。
接下来,我们使用 `while` 循环,每次循环时,提示用户输入密码。如果输入的密码与正确的密码相同,则输出一条消息表明密码正确,然后跳出循环。否则,输出一条消息表明密码不正确,并减少变量 `attempts` 的值。在循环结束时,我们检查 `attempts` 的值,如果为零,则表明用户已经用完了所有的尝试次数,我们输出一条消息表明访问被拒绝。最后,我们关闭 `Scanner` 对象。