Search code examples
javainttype-conversionjtextfieldjoptionpane

Converting from String to Int


I'm trying to validate my program by entering a value through a JTextField on a JDialog and if it's less than a value..., else do ... I keep running into a problem on the line:

int intDiagInput = Integer.parseInt(dialogInput)

JOptionPane.showInputDialog(dialogPaneInput, "Age verification required, please enter year of birth: yyyy");

            dialogInput = dialogPaneInput.getText(); //get info from JTextField and put in string

            int intDiagInput = Integer.parseInt(dialogInput); //convert string to int

Any help would be greatly appreciated.


Solution

  • Your code is wrong in two ways: The first paramenter you pass to showInputDialog is used as the parent, just for layout purposes, it has nothing to do with the actual content of the input dialog. Therefore your second error is getting the text from the displayed dialog. To get the text the users enters you need to write something like:

    String dialogInput = JOptionPane.showInputDialog(dialogPaneInput, "Age verification required, please enter year of birth: yyyy");
    
    int intDiagInput = Integer.parseInt(dialogInput ); //convert string to int
    

    What you are doing is getting the text of some magical object dialogPaneInput, which probably is just an empty string.

    Additionally you should check that the user inputs a valid number, not in terms of a number that you would accept but in terms of it actually beeing a number, otherwise you will run into the already existent NumberFormatException - or wrap the parsing in a try...catch-block.

    try {
        int intDiagInput = Integer.parseInt(dialogInput );
    } catch (NumberFormatException nfex) {
        System.err.println("error while trying to convert input to int.");
    }