[英]giving a null value to a int type variable
我是 Java 新手,我已經搜索了 2 天如何實現這一點,但仍然沒有弄清楚。 在我的 if 語句中,我需要確保如果用戶只按 Enter 鍵而不輸入值,則消息將提示重新輸入,如果用戶輸入的值小於 1。下面是我的代碼片段。 我已經閱讀了 int cant except null,並且我嘗試了 Integer ,但是我的代碼不會運行
int numberOfCars = -1
while (numberOfCars == null || numberOfCars < 1)
{
numberOfCars = (JOptionPane.showInputDialog("Enter number of cars."));
if(numberOfCars == null || numberOfCars < 1)
{
JOptionPane.showMessageDialog(null, "Please enter a value.");
}
}
int numberOfCars = -1;
do {
String answer = JOptionPane.showInputDialog("Enter number of cars.");
if (answer != null && answer.matches("-?[0-9]+")) {
numberOfCars = Integer.parseInt(answer);
if (numberOfCars < 1) {
JOptionPane.showMessageDialog(null, "Value must be larger than 1.");
}
} else {
JOptionPane.showMessageDialog(null, "Value not a number.");
}
} while (numberOfCars < 1);
這會進行驗證( matches
),否則parseInt
會拋出NumberFormatException
。
正則表達式String.matches(String)
.matches("-?[0-9]+")
這與模式匹配:
-?
= 減號,可選 ( ?
)[0-9]+
= 來自[ ... ]
一個字符,其中 0-9 是范圍、數字以及一次或多次 ( +
)有關正則表達式的信息,另請參閱模式。
Integer.parseInt(string)
給出從字符串中獲取的int
值。 就像除以零一樣,這會引發錯誤,即 NumberFormatException。
此處適合使用 do-while 循環(很少適用)。 正常的 while 循環也可以。
JOptionPane.showInputDialog()
將返回一個String
。 當您嘗試使用Integer.parseInt()
將其解析為int
時,您可以使用try-catch
語句來檢查輸入值是否正確。 這將適用於您的所有情況。
所以這可以工作:
int numberOfCars = -1;
while(numberOfCars < 1){
try{
numberOfCars = JOptionPane.showInputDialog("Enter number of cars.");
if(numberOfCars < 1){
JOptionPane.showMessageDialog(null, "Please enter a value.");
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please enter numeric value.");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.