我有来自 JTextField 的字符串输入,它必须是带数字的小数输入,由单个“/”分隔。
当用户输入错误的字符串时,我需要抛出一个错误;到目前为止,我可以匹配模式,但不会抛出异常。不知道我做错了什么,或者是否有更简单的方法(不过我需要使用 try-catch);
public void setInputData(String strFrac1, String strFrac2, String oper)
{
String test1, test2;
test1 = strFrac1;
test2 = strFrac2;
try
{
test1.matches("(d+)(p/)(d+)");
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null, e.getMessage(), "ALERT!", JOptionPane.ERROR_MESSAGE);
}
String[] fraction2 = strFrac2.split("/");
String[] fraction1 = strFrac1.split("/");
//This will fill up a single array with the numbers and operators we need to use
for (int i = 0 ; i <= 1; i++)
{
fractions[i] = fraction1[i];
if (i == 0 || i == 1)
{
fractions[i + 2] = fraction2[i];
}
}
fractions[4] = oper;
return();
}
我是不是用错了捕手?
最佳答案
test1.matches("(d+)(p/)(d+)");
将返回一个 boolean 值
你可以显式地抛出一个异常
try
{
if(!test1.matches("(d+)(p/)(d+)"))
throw new NumberFormatException();
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null, e.getMessage(), "ALERT!", JOptionPane.ERROR_MESSAGE);
}
关于java - 在 Java 中使用 try-catch 从 JTextField 中捕获分数的字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17228796/