![](/img/trans.png)
[英]Exception in thread “main” java.lang.NumberFormatException: For input string: “” in Java
[英]java - Exception in thread “main” java.lang.NumberFormatException: For input string: “” at
我試圖運行以下示例,如果我在整數框/字段中輸入字母或選擇“確定/取消”而不輸入值,則會退出確定或強制您輸入有效的數字值。
對於文本字段,它可以正常工作,但不能用於整數,但出現以下錯誤。
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
for this code, is it possible to achieve what I want? thanks for any answers in advance
import javax.swing.*;
public class Methods
{
public static void main(String[] args)
{
//THIS IS FOR THE 1ST POP UP BOX
// prompt the user to enter their name
String name = JOptionPane.showInputDialog( "What is your Firstname?");
// get the user's input. note that if they press Cancel, 'name' will be
null
System.out.printf("The user's name is '%s'.\n", name);
//
//THIS IS FOR THE 2ND POP UP BOX
// prompt the user to enter their name
String nametwo = JOptionPane.showInputDialog(frametwo, "What is your
Surname?");
// get the user's input. note that if they press Cancel, 'name' will be
null
System.out.printf("The user's name is '%s'.\n", nametwo);
//
//THIS IS FOR THE 3RD POP UP BOX
// prompt the user to enter their age
int namethree = Integer.parseInt(JOptionPane.showInputDialog(framethree,
"How old are you?"));
//if (num.isEmpty())
// get the user's input. note that if they press Cancel, 'age' will be
null
System.out.printf("Your age is '%s'.\n", namethree);
System.out.println("********************************");
System.exit(0);
}
}
您需要在對Integer.parseInt的調用周圍添加異常處理以捕獲轉換錯誤-此方法將為無法轉換為Integer的任何字符串引發NumberFormatException。
就像是:
try
{
int namethree = Integer.parseInt(JOptionPane.showInputDialog(framethree,
"How old are you?"));
}
catch (NumberFormatException)
{
//TODO: display an error message and retry the input
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.