2014-11-01 96 views
0

我正在寻找有关如何捕获用户输入的无效字符串的异常。我有一个例外的整数输入以下代码:Java捕获异常 - 空字符串

  try { 
      price = Integer.parseInt(priceField.getText()); 
      } 
      catch (NumberFormatException exception) { 
      System.out.println("price error"); 
      priceField.setText(""); 
      break; 

但我不知道字符串特定异常,输入是一个简单的JTextBox所以只能输入不正确,我能想到的是,如果用户什么都不输入,这正是我想要捕捉的。

回答

6
if (textField.getText().isEmpty()) 

是你所需要的。

或许

if (textField.getText().trim().isEmpty()) 

,如果你也想测试空白输入,只包含空格/制表符。

您通常不会使用异常来测试值。测试字符串是否代表整数是规则的例外,因为String中没有可用的isInt()方法。

0

你可以这样做

if (priceField.getText().isEmpty()) 
    throw new Exception("priceField is not entered."); 
1

您可以检查是否priceField包含字符串使用此:

JTextField priceField; 
int price; 
try { 
// Check whether priceField.getText()'s length equals 0 
if(priceField.getText().getLength()==0) { 
    throw new Exception(); 
} 
// If not, check if it is a number and if so set price 
price = Integer.parseInt(priceField.getText()); 
} catch(Exception e) { 
// Either priceField's value's length equals 0 or 
// priceField's value is not a number 

// Output error, reset priceField and break the code 
System.err.println("Price error, is the field a number and not empty?"); 
priceField.setText(""); 
break; 
} 

当if语句为真(如果priceField.getText()长度为0)抛出异常,这将触发catch-block,发出错误,重置priceFieldbreak的代码。

如果if语句虽然为假(如果priceField.getText()的长度大于或小于0),它将检查priceField.getText()是否是一个数字,如果是,则将price设置为该值。如果它不是一个数字,则抛出一个NumberFormatException异常,这将触发catch-block等。

让我知道它是否有效。

编码愉快:) -Charlie

如果你想在Java虚拟机的正常运行期间抛出你的异常
+4

这是如此丑陋... – slnowak 2014-11-01 19:37:35

1

,那么你可以使用这个

if (priceField.getText().isEmpty()) 
    throw new RunTimeException("priceField is not entered.");