【问题标题】:Java, while loop with scanner inside and as a statementJava,内部带有扫描仪的while循环并作为语句
【发布时间】:2017-09-18 15:43:01
【问题描述】:

尝试运行 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!");
}

【问题讨论】:

  • “尝试在循环之外声明它” haslo = reader.nextLine();
  • 因为您试图在声明 haslo 之前读取它的值...
  • 侧栏:循环必须至少执行一次。考虑改为 do-while 循环。

标签: java loops while-loop


【解决方案1】:
  1. 在循环开始之前将变量 haslo 声明为String haslo = "";
  2. 在循环中,将您的行 String haslo = reader.nextLine(); 替换为 haslo = reader.nextLine();

推理

For 1 --> 您的while 循环在声明变量之前引用了变量haslo。所以需要在被引用之前声明一下。

For 2 --> 一旦它被声明,你就不想重新声明它,因为在循环之前声明的那个已经在循环范围内可用了。

【讨论】:

    【解决方案2】:

    这都是关于范围的。

    您的haslo 变量在inside while 循环中声明,因此只能在声明后inside 使用。 while 循环的条件是在声明 haslo 之前评估的,因此您不能在那里使用 haslo

    要解决此问题,请在 while 循环外声明 haslo

    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】:

      你能试试这样的吗?需要在循环前声明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】:

        循序渐进可以找到问题:

        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】:

          再次声明字符串 INSIDE 循环!否则下次循环将不起作用!你给了它一个参考,但循环需要再次知道参考是什么。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-11-25
            • 2019-11-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多