4 Replies Latest reply: Dec 9, 2007 9:11 PM by 807601 RSS

    boolean statements

      how would I create a boolean statement that returns true when a int value is parseable from a string:
      For example: the string "1234" can be parsed and the int value can be 1234. This is what I've thought of so far:
      if (Integer.parseInt(button[i][j].getText()) instanceof int) {
        • 1. Re: boolean statements
          Use a try statement surrounding the parseint statement.
          • 2. Re: boolean statements
            to demonstrate concretely what Quacked recommends:
                    boolean textfieldParseable = false;
                        int myInt = Integer.parseInt(myTextField.getText());
                        // if parsing fails, the line below is never reached
                        textfieldParseable = true; 
                    catch (NumberFormatException e)
                        JOptionPane.showMessageDialog(null, "Please enter only integer data", 
                                "Non-Integer Data Entered", JOptionPane.ERROR_MESSAGE);
            Addendum: If you give out Dukes for these posts (and you should), please give them to Quacked as this idea was originally his, not mine.

            Edited by: petes1234 on Dec 9, 2007 6:59 PM
            • 3. Re: boolean statements
              Or use a regular expression.
              if (theString.matches("\\d+")) {
                // just a sequence of digits -- safe to parse
              • 4. Re: boolean statements
                If a string IS NOT parseable, the method "Integer.parseInt" would throw an "NumberFormatException". Therefore, we only have to test if an exception is thrown or not.
                public class Main {
                    public static void main(String[] args) {
                        public static boolean parsableTest(String j){
                        boolean parsable=true;
                        try {int i; i=Integer.parseInt(j);}
                        catch (NumberFormatException nfe){parsable=false;}
                        return parsable;