I am trying to program a simple calculator.
public static String cal(){
String a="-60-1+40";
if(a.matches("-?[1-9][0-9]?([\\+-][1-9][0-9]?)+")){
System.out.println(a);
String operators[]=a.split("[0-9]+");
String operands[]=a.split("[+-]");
int agregate = Integer.parseInt(operands[0]);
for(int i=1;i<operands.length;i++){
if(operators[i].equals("+"))
agregate += Integer.parseInt(operands[i]);
else
agregate -= Integer.parseInt(operands[i]);
}
return Integer.toString(agregate);
}else throw new invalidExpressionException(a+" is a Invalid expression");
}
I have this function but when I try to run it I get a NumberFormatException
if the first character of the string is a "-"
. All other cases seems to be right and only that one is failing. I've been trying to fix for a while but I don't find how.
run:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
-60-1+40
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at calculator.Calculator.cal(Calculator.java:20)
at calculator.Calculator.main(Calculator.java:9)
Following @Ben's comment, a workaround would be to check if the first character is a '-
', and in that case preppend a 0
to the string before processing it (-n can be obtained as sustracting the number n from 0):
-1+2-3
, should become 0-1+2-3
if(a.startsWith("-")){
a = "0" + a;
}