简体   繁体   中英

Conditions regarding parsed integer from JTextField

In my program I get the value of JTextField and parse into an integer:

String string = jtext.getText();
int stringval = Integer.parseInt(str);

My question is how to I'm a able to check if the value was parsed into an integer? I tried this, but it didn't hold the results I wished to accomplished and I received errors.

if(str == null)
  {
      JOptionPane.showMessageDialog(null, "Integer not parsed", "Message",
      JOptionPane.INFORMATION_MESSAGE);
  }

If it wasn't able to be parsed into an int it would throw an exception.

Try using a try catch statement

boolean tryParseInt(String value)  
{  
     try  
     {  
         Integer.parseInt(value);  
         return true;  
      } catch(NumberFormatException nfe)  
      {  
          return false;  
      }  
}

You could use it like this

if(tryParseInt(myInput))
{  
   Integer.parse(myInput); 
}

or if you want to do it without a method

int stringval;
bool success = true;

try
{
  stringval = Integer.parseInt(str);
}
catch (NumberFormatException nfe)  
{
  success = false;
  JOptionPane.showMessageDialog(null, "Integer not parsed", "Message",
  JOptionPane.INFORMATION_MESSAGE);
}

if (success)
{
  //do whatever
}

Hope that helps

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