# indicates decimal entry to disambiguate from default hex entry.
/**
MacsBug style number display and simple (hex/)integer calculation
Numbers assumed to default to hex, # must be prefixed for decimal,
10 = #16,
#-15 for -15.
Calculations are strictly left to right with no precedence 2 + 3 * 4
= 20 not 14
**/
public class mbeval {
public static void main(String [] args) {
int num;
char op = ' ';
if (args.length == 0) {
System.out.println("mbeval: No input");
return;
}
num = getNum(args[0]);
if (args.length > 1) {
for (int i=1; i<args.length;) {
try { op = getOp(args[i++]); }
catch (IllegalArgumentException iae) {
System.out.println("mbeval: [Invalid Operation] ");
return;
}
if (i > args.length) {
System.out.println("mbeval: [Incomplete expression] ");
}
num = doop(num,op,getNum(args[i++]));
}
}
print(num);
}
static char getOp(String s) {
if (s.length() > 1) throw new IllegalArgumentException(s);
char c = s.charAt(0);
if (c != '+' && c != '-' && c != '*' && c != '/') throw new
IllegalArgumentException(s);
return c;
}
static int doop(int num, char op, int operand) {
if (op == '+') return num + operand;
if (op == '-') return num - operand;
if (op == '*') return num * operand;
return num / operand;
}
static int getNum(String s) {
int num = 0, radix = 10;
try {
if (!s.startsWith("#")) radix = 16;
else s = s.substring(1); // Strip the # prefix
return Integer.parseInt(s,radix);
}
catch (NumberFormatException nfe) {}
return num;
}