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 txt box valadation?

Options
  • 17-01-2004 12:55am
    #1
    Closed Accounts Posts: 1,637 ✭✭✭


    OK I need to valadate a InputDialog box so it can only accept a number, so no letters or letters&numbers.

    Heres what I got so far,


    import javax.swing.JOptionPane;

    public class valadation {

    public static void main(String[] args) {

    int num;
    String choice;
    int result;

    choice = JOptionPane.showInputDialog(
    "Enter Number");

    while (choice == ""){
    JOptionPane.showMessageDialog(null,
    "Error, Numbers only");
    }

    while (choice == null){
    JOptionPane.showMessageDialog(null,
    "Error, Numbers only");

    choice = JOptionPane.showInputDialog(
    "Enter Number");

    }


    while (choice.matches("\\D+")){

    JOptionPane.showMessageDialog(null,
    "Error, Numbers only");

    choice = JOptionPane.showInputDialog(
    "Enter Number");
    }


    num = Integer.parseInt(choice);

    result = square(num);

    JOptionPane.showMessageDialog( null,
    "Result = " + result, "Result",
    JOptionPane.PLAIN_MESSAGE );

    //System.out.print(result);

    System.exit( 0 );

    }

    public static int square(int x){//Method Call

    return x * 6;

    }

    }


    OK it works if I enter a number, and gives the error message if I enter a letter, but any other combination it crashes???

    Theres also a method you can ignore that. "Sorry"

    Thanks loads in advance........

    Thanks joePC


Comments

  • Registered Users Posts: 6,316 ✭✭✭OfflerCrocGod


    Jesus boy use the Force!!!....RegExp (Regular Expresions).


  • Registered Users Posts: 6,316 ✭✭✭OfflerCrocGod


    import javax.swing.JOptionPane;

    public class valadation {

    public static void main(String[] args) {

    int num;
    String choice;
    int result;

    choice = JOptionPane.showInputDialog("Enter Number");

    while ( !choice.matches("[0-9]+" ) ){
    JOptionPane.showMessageDialog(null,"Error, Numbers only");
    choice = JOptionPane.showInputDialog("Enter Number");
    }

    num = Integer.parseInt(choice);
    result = square(num);

    JOptionPane.showMessageDialog( null,"Result = " + result, "Result", JOptionPane.PLAIN_MESSAGE );

    System.exit( 0 );
    }

    public static int square(int x){//Method Call
    return x * 6;
    }
    }

    Should work, test it.


  • Closed Accounts Posts: 1,637 ✭✭✭joePC


    Thanks alot OfflerCrocGod,

    Its always the small things :)

    ( !choice.matches("[0-9]+" ) )

    Thanks joePC


Advertisement