代码之家  ›  专栏  ›  技术社区  ›  Maciaz

Java,while循环,其中包含scanner并作为语句

  •  1
  • Maciaz  · 技术社区  · 7 年前

    尝试运行while循环进行密码检查。我确实不断得到一个错误,变量haslo找不到。尝试在循环外声明它-然后它说,它已经声明了。我知道可以用无限循环和break命令来完成。我只是好奇这样是否可行。

    String password = "pw123";
    
    while (!haslo.equals(password)){
    
            System.out.println("Enter pw:");
            String haslo = reader.nextLine();
    
            if (haslo.equals(password))
                System.out.println("Right!");
    
            else
                System.out.println("Wrong!");
    }
    
    5 回复  |  直到 7 年前
        1
  •  2
  •   VHS    7 年前
    1. 将变量haslo声明为 String haslo = ""; 在循环开始之前。
    2. 在循环中,更换您的线路 String haslo = reader.nextLine(); haslo = reader.nextLine();

    推理 :

    while 循环在声明变量haslo之前引用该变量。因此,您需要在引用它之前声明它。

        2
  •  0
  •   Sweeper    7 年前

    这都是关于范围的。

    你的 haslo 变量已声明 while循环和so只能使用 在…内 所以你不能用 哈斯洛 那里

    哈斯洛 在while循环之外:

    String haslo = "";
    while (!haslo.equals(password)){
    
        System.out.println("Enter pw:");
        haslo = reader.nextLine(); // <-- note that I did not write "String" here because that will declare *another* variable called haslo.
    
        if (haslo.equals(password))
            System.out.println("Right!");
    
        else
            System.out.println("Wrong!");
    }
    
        3
  •  0
  •   derOtterDieb    7 年前

    你能试试这样的吗?您需要在循环之前声明haslo,然后可以在循环内使用它,并避免无限循环。

    String password = "pw123";
    String haslo = "";
    
    while (!haslo.equals(password)){
    
        System.out.println("Enter pw:");
        haslo = reader.nextLine();
    
        if (haslo.equals(password))
            System.out.println("Right!");
    
        else
            System.out.println("Wrong!");
    
    }
    
        4
  •  0
  •   JustinKSU    7 年前

    问题可以通过循序渐进的方式找到:

    String password = "pw123"; (Good)
    
    while (!haslo.equals(password)){ (Bad. What is Haslo? It is not defined before you use it here)
    

    试试这个:

    String password = "pw123";
    String haslo = "";
    while (!haslo.equals(password)){
        System.out.println("Enter pw:");
        haslo = reader.nextLine();
    
        if (haslo.equals(password))
            System.out.println("Right!");
    
        else
            System.out.println("Wrong!");
    
    }
    
        5
  •  0
  •   Ella    7 年前