繁体   English   中英

执行方法时布尔值不保存值

[英]boolean not holding value when method is executed

我有一种遇到问题的方法。 下面的第二个方法hintForForPinNumber()调用第一个方法canConvertToInteger(),然后根据布尔变量pinValid的值是true还是false来执行操作。

当我自己执行方法canConvertToInteger()时,它的功能很好,并且pinValid的值正确。

当我执行hintForForPinNumber()并输入一个引发异常的字符串时,pinValid的值保持为true,因此if else块的else部分未执行,但是pinTry的值为0,因此必须有一个异常已经被抓到并处理了。 那么为什么当pinValid的布尔值应该为false时才为true?

应该发生的情况是,如果在OUDialog.request框中输入了无效的条目,则应将pinValid设置为false,然后应将pinTry的值更改为0,并且

  public boolean canConvertToInteger()
   {
      String pinAttempt;
      {
         pinAttempt = OUDialog.request("Enter your pin number");
         try
         {
            this.pinTry=Integer.parseInt(pinAttempt);
            this.pinValid = true;
         }
          catch (NumberFormatException anException)
        {
            this.pinTry=0;
            this.pinValid = false;
        }
      }
       return this.pinValid;
   }

  public int promptForPinNumber()
       {
          this.canConvertToInteger();
          if (pinValid = true)
          {
             return this.pinTry;
          }
           else
          {
             OUDialog.alert("Number entered is not a valid pin");
             return this.pinTry;
          }
       }

经典一,更换

if (pinValid = true)

与:

if (pinValid == true)

甚至更好:

if (pinValid)

pinValid = 1赋值 ,而不是表达式(条件)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM