[英]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
的文本,該文本可能只是一個空字符串。
另外,您應該檢查用戶是否輸入了有效的數字,而不是根據您接受的數字,而是根據它實際是一個數字,否則,您將遇到已經存在的NumberFormatException
或try...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.