I have the string input from a JTextField, It will have to be a fractional input with numbers, separated by a single '/'.
I need to throw an error when a user inputs a string incorrectly; so far I can match the pattern but the exception won't get thrown. No idea what I'm doing wrong or if there is an easier way to do it, (I need to use try-catch though);
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();
}
Am I using the wrong catcher?
test1.matches("(d+)(p/)(d+)");
will return a boolean
you can explicitily throw an exception
try
{
if(!test1.matches("(d+)(p/)(d+)"))
throw new NumberFormatException();
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null, e.getMessage(), "ALERT!", JOptionPane.ERROR_MESSAGE);
}