简体   繁体   中英

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.

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.");
}

The exception you posted on the comment section (java.lang.NumberFormatException: For input string: "") means that you're trying to convert an empty String to int.

Change your code to verify if dialogInput is not empty before converting it to int.

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