简体   繁体   中英

boolean not holding value when method is executed

I have a method that I am having a problem with. The second method below, promptForPinNumber(), calls the first method, canConvertToInteger(), and then carries out an action, dependent on whether the value of the Boolean variable, pinValid, is true or false.

When I execute the method canConvertToInteger() on its own, it functions fine, and the value of pinValid is correct.

When I execute promptForPinNumber(), and enter a string that throws and exception, the value of pinValid stays true, so the else section of the if else block isn't executed, however, the value of pinTry is 0, so an exception must have been caught and dealt with. So why is the Boolean for pinValid true when it should be false?

What should happen is that if an invalid entry is made into the OUDialog.request box, then pinValid should be set to false, which should then change the value of pinTry to 0, and

  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;
          }
       }

Classic one, replace

if (pinValid = true)

with:

if (pinValid == true)

or even better:

if (pinValid)

pinValid = 1 is an assignment , not an expression (condition).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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