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;对于(n> 3; n ++)"但它并没有像预期的那样发挥作用
答案 0 :(得分:2)
您应该为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
}
答案 1 :(得分:1)
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int maxAttempts = 3;
while (maxAttempts > 0) {
System.out.print("Type password:\t");
String command = reader.nextLine();
if (command.equals("carrot")) {
System.out.println("Right!");
break;
} else{
System.out.println("Wrong!");
System.out.println("The secret is: jryy qbar!");
maxAttempts--;
if(maxAttempts == 0){
System.out.println("You have reached the max number of attempts!");
}
}
}
reader.close();
}
答案 2 :(得分:0)
def calc(request):
form = CalcForm(request.GET)
if form.is_valid():
# all fields are valid
data = form.cleaned_data
答案 3 :(得分:0)
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
while (true) {
System.out.print("Type password:\t");
String command = reader.nextLine();
if (command.equals("carrot")) {
System.out.println("Right!");
System.out.println("The secret is: jryy qbar!");
break;
} else {
i++;
System.out.println("Wrong!");
if (i == 3) {
System.out.println("Max attempts reached!! Exiting....");
break;
}
}
}
reader.close();
}