Search code examples
javaintparseint

change value of an integer using parseInt


So I'm writing a method that is supposed to prompt the user to enter their pin number as a string, which is then converted to an int (or not depending on if it throws an exception), which I need to be assigned to the int pinNumber.

The problem I'm having is that the new object is assigned a pin number by the constructor when created, and this value isn't being changed when the below method is executed. What am I missing?

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

EDIT: Changed pinAttempt to pinNumber (typo)


Solution

  • Have a look at this block

    try
    {
       int pinNumber = Integer.parseInt(pinAttempt);
       return true;
    }
    

    pinNumber will only have the value you expect in the scope of the try block.

    I think you want to do

    try
    {
       this.pinNumber = Integer.parseInt(pinAttempt);
       return true;
    }
    

    instead.