Improved error messages

This commit is contained in:
Norbi Peti 2016-07-20 09:55:24 +02:00
parent fd2d489480
commit 83e92859aa
2 changed files with 17 additions and 14 deletions

View file

@ -14,18 +14,14 @@ public class Calc {
private static final Pattern PARENTHESIS = Pattern.compile("\\(([^()]+)\\)");
public static Double calculate(String text) {
public static String calculate(String text) {
StringBuffer buf = new StringBuffer(text);
replace(buf, PARENTHESIS, (a) -> calculate(a));
replace(buf, MULTIPLY, (a, b) -> a * b);
replace(buf, DIVIDE, (a, b) -> a / b);
replace(buf, ADD, (a, b) -> a + b);
replace(buf, SUBTRACT, (a, b) -> a - b);
try {
return Double.parseDouble(buf.toString());
} catch (Exception e) {
return null;
}
return buf.toString();
}
private static void replace(StringBuffer buf, Pattern pattern, BiFunction<Double, Double, Double> doit) {
@ -38,12 +34,12 @@ public class Calc {
}
}
private static void replace(StringBuffer buf, Pattern pattern, Function<String, Double> doit) {
private static void replace(StringBuffer buf, Pattern pattern, Function<String, String> doit) {
while (true) {
Matcher matcher = pattern.matcher(buf.toString());
if (!matcher.find())
break;
buf.replace(matcher.start(), matcher.end(), Double.toString(doit.apply(matcher.group(1))));
buf.replace(matcher.start(), matcher.end(), doit.apply(matcher.group(1)));
}
}
}

View file

@ -118,13 +118,20 @@ public class Gui {
tf.setText("0.0");
return;
}
Double ret = Calc.calculate(tf.getText());
if (ret == null)
JOptionPane.showMessageDialog(frame,
"Unable to convert result to number!\nThis is usually caused by a mistype, like \"5++5\"",
"Error!", JOptionPane.WARNING_MESSAGE);
String result = Calc.calculate(tf.getText());
String errormsg = "Unbalanced parenthesis: ";
int openc = result.length() - result.replace("(", "").length();
int closec = result.length() - result.replace(")", "").length();
if (openc - closec > 0)
errormsg += "There is " + (openc - closec) + " more of ( than )";
else if (openc - closec < 0) {
errormsg += "There is " + (closec - openc) + " more of ) than (";
} else
errormsg = "";
if (errormsg.length() == 0)
tf.setText(Double.toString(Double.parseDouble(result)));
else
tf.setText(Double.toString(ret));
JOptionPane.showMessageDialog(frame, errormsg, "Error!", JOptionPane.WARNING_MESSAGE);
} catch (ArithmeticException e) {
JOptionPane.showMessageDialog(frame, "Arithmetic error: " + e.getMessage(), "Error!",
JOptionPane.WARNING_MESSAGE);