Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

JAVA string validation

Options
  • 30-11-2005 12:53pm
    #1
    Registered Users Posts: 849 ✭✭✭


    Im doing some string validation to validate for only numbers as seen below. Im prob doing somthing quite silly but when I enter a number above 9 ie 10 + my code loops back around again. Anyone got any ideas?

        public static int valid(String string) {
            
            String text;
            int option = 0;
            
            text = JOptionPane.showInputDialog(string);
            
            while (option < 1) {
    
                while (!text.matches("\\d")) {
                    
                        JOptionPane.showMessageDialog(null, "Invalid selection please try again.", "xxx", JOptionPane.ERROR_MESSAGE);
                    
                        text = JOptionPane.showInputDialog(string);
                        
                        if (text == null) {
    
                            JOptionPane.showMessageDialog(null, "Invalid selection please try again.", "xx", JOptionPane.ERROR_MESSAGE);
                            
                            menu();    
                            
                        }
                 
                }
                
                option = Integer.parseInt(text);
                
            }
            
            return option;
            
        }
    
    


Comments

  • Registered Users Posts: 21,264 ✭✭✭✭Hobbes


    while (!text.matches("\\d")) {

    \\d refers only to one digit. For ten you would need "\\d\\d".


  • Registered Users Posts: 4,188 ✭✭✭pH


    How about ...
    "\\d\\d*"
    
    to match any valid number (1 digit or more)


  • Registered Users Posts: 849 ✭✭✭Cr8or


    nice one thanks .. thought that might be the problem .. wasnt sure how to get around it.

    its working now :) this also seemed to work.
    \\d*
    


  • Registered Users Posts: 3,548 ✭✭✭Draupnir


    \\d* may return true for 0 instances of the digit I believe, so beware of false positives.


  • Closed Accounts Posts: 89 ✭✭ishnid


    Yeah - \\d* also matches empty strings, use \\d+


  • Advertisement
Advertisement