从字符串转换为 Int
Converting from String to Int
我正在尝试通过 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
如有任何帮助,我们将不胜感激。
您在评论部分发布的异常 (java.lang.NumberFormatException: For input string: "") 意味着您正在尝试将空字符串转换为 int。
更改代码以在将 dialogInput 转换为 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
块中。
try {
int intDiagInput = Integer.parseInt(dialogInput );
} catch (NumberFormatException nfex) {
System.err.println("error while trying to convert input to int.");
}
我正在尝试通过 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
如有任何帮助,我们将不胜感激。
您在评论部分发布的异常 (java.lang.NumberFormatException: For input string: "") 意味着您正在尝试将空字符串转换为 int。
更改代码以在将 dialogInput 转换为 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
块中。
try {
int intDiagInput = Integer.parseInt(dialogInput );
} catch (NumberFormatException nfex) {
System.err.println("error while trying to convert input to int.");
}