gpt4 book ai didi

java - 如何向此 java 代码添加尝试次数

转载 作者:行者123 更新时间:2023-12-01 21:22:41 26 4
gpt4 key购买 nike

public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
while (true) {
System.out.print("Type password:\t");
String command = reader.nextLine();
if (command.equals("carrot")) {
break;

} else {
System.out.println("Wrong!");
}

}
System.out.println("Right!");
System.out.println("The secret is: jryy qbar!");
reader.close();
}

我想在这里添加最多 3 次尝试,我尝试了不同的组合,例如“int n = 0; for (n>3; n++)”,但它并没有真正按预期工作

最佳答案

您应该在 while 子句中添加条件。

import java.util.Scanner; public class Main {

public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
boolean isPasswordCorrect = false;
while (i++ < 3) {
System.out.print("Type password:\t");
String command = reader.nextLine();
if (command.equals("carrot")) {
isPasswordCorrect = true;
break;
} else{
System.out.println("Wrong!");
}
}
if(isPasswordCorrect) {
System.out.println("Right!");
System.out.println("The secret is: jryy qbar!");
}
reader.close();
}
}

PROTIP:扫描仪实现 AutoCloseable ,因此您可以使用 try-with-resources这里:

try (Scanner reader = new Scanner(System.in)) {
// your code using scanner
}

关于java - 如何向此 java 代码添加尝试次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38891087/

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