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

标签 java

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/

相关文章:

java - 使用 XMLUnit 忽略大小写

Java继承和理解接口(interface)类

java - 为什么整数 div 和 mod 向零舍入?

java - AutoCloseable.close()方法是否违反了Java的向后兼容性规则

java - 在 MVC 中,与应用程序模型相反的 GUI 模型是什么?

java - 关键的 gemfire 负载测试

java - 如何设置单元格背景颜色(JavaFX,tableview)

java - 如何从所有按钮打印文本?

java - 根据用户选择的选项在另一个类中使用字符串

java - Hibernate - 一对多关系和 orphanRemoval 级联