我试图通过在 JDialog 上的 JTextField 输入一个值来验证我的程序,如果它小于一个值...,否则...我一直遇到问题:
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
任何帮助将不胜感激。
最佳答案
您的代码有两个错误:
您传递给 showInputDialog
的第一个参数用作父级,仅用于布局目的,与输入对话框的实际内容无关。因此,您的第二个错误是从显示的对话框中获取文本。
要获取用户输入的文本,您需要编写如下内容:
String dialogInput = JOptionPane.showInputDialog(dialogPaneInput, "Age verification required, please enter year of birth: yyyy");
int intDiagInput = Integer.parseInt(dialogInput ); //convert string to int
你正在做的是获取一些神奇对象dialogPaneInput
的文本,它可能只是一个空字符串。
此外,您应该检查用户输入的数字是否有效,不是您接受的数字,而是它实际上是一个数字,否则您将遇到已经存在的 NumberFormatException
- 或将解析包装在 try...catch
block 中。
try {
int intDiagInput = Integer.parseInt(dialogInput );
} catch (NumberFormatException nfex) {
System.err.println("error while trying to convert input to int.");
}
关于java - 从字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28950066/