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);   
}

其他提示

There is no problem with the line

test1.matches("(d+)(p/)(d+)");

It will return either true or false. But will not throw any exception .

to do this you can check the boolean value of mathes method

if(!test1.matches("(d+)(p/)(d+)")
    // show the dialog

If you want to throw the exception when it does not match the pattern, then you need to throw it explicitly. The signature of matches method is

public boolean matches(String regex)

This means it will return true or false

so if your pattern matches the string input, then it will return true or it will return false.

To solve your problem, you can do,

 if(test1.matches("(d+)(p/)(d+)")){
 // domeSomething
 }else {
  throw new NumberFormatException();
 }

This is the case where you have to use try-catch, if you don't want to use it, then you can simply show MessageDialog as follows

 if(test1.matches("(d+)(p/)(d+)")){
  //doSomething
  }else{
       JOptionPane.showMessageDialog(null, e.getMessage(), "ALERT!",   JOptionPane.ERROR_MESSAGE);   

  }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top