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/