1

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?

4

3 に答える 3

3

ラインも問題なし

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

trueまたはのいずれかを返しますfalse。しかし、何もスローしませんexception

mathesこれを行うには、メソッドのブール値を確認できます

if(!test1.matches("(d+)(p/)(d+)")
    // show the dialog
于 2013-06-21T06:16:58.877 に答える
3
test1.matches("(d+)(p/)(d+)");

ブール値を返します

明示的に例外をスローできます

try 
{
if(!test1.matches("(d+)(p/)(d+)"))
     throw new NumberFormatException();
}
catch (NumberFormatException e) 
{
JOptionPane.showMessageDialog(null, e.getMessage(), "ALERT!", JOptionPane.ERROR_MESSAGE);   
}
于 2013-06-21T06:22:59.873 に答える
2

パターンに一致しない場合に例外をスローする場合は、明示的にスローする必要があります。matchesメソッドのシグネチャは

public boolean matches(String regex)

これは、それが戻るtrueか、false

したがって、パターンが文字列入力と一致する場合は、それが返されるtrueか、返されfalseます。

問題を解決するには、次のことができます。

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

これは、 を使用する必要があるtry-catch場合です。使用したくない場合は、次のように単純に表示できMessageDialogます。

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

  }
于 2013-06-21T06:20:06.853 に答える