繁体   English   中英

从String转换为Int

[英]Converting from String to Int

我试图通过在JDialog上通过JTextField输入一个值来验证我的程序,如果它小于一个值...,否则执行...我一直在网上遇到问题:

int intDiagInput = Integer.parseInt(对话框输入)

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的文本,该文本可能只是一个空字符串。

另外,您应该检查用户是否输入了有效的数字,而不是根据您接受的数字,而是根据它实际是一个数字,否则,您将遇到已经存在的NumberFormatExceptiontry...catch进行解析try...catch

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

您在注释部分发布的异常(java.lang.NumberFormatException:对于输入字符串:“”)表示您正在尝试将空String转换为int。

更改代码以在将dialogInput转换为int之前验证dialogInput是否为空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM