On Tuesday, we (mostly) finished the simple calculator example that we started in week 2.
Here's one version we came up with that allows unlimited precision integer arithmetic:
import java.math.BigInteger;
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String prompt = "> ";
System.out.print(prompt);
while (input.hasNext()) {
if (input.hasNext("quit")) {
break;
}
BigInteger x = input.nextBigInteger();
String operator = input.next();
BigInteger y = input.nextBigInteger();
BigInteger result = BigInteger.ZERO;
if (operator.equals("+")) {
result = x.add(y);
} else if (operator.equals("*")) {
result = x.multiply(y);
} else if (operator.equals("/")) {
result = x.divide(y);
} else if (operator.equals("-")) {
result = x.subtract(y);
} else if (operator.equals("**")) {
int yint = y.intValue();
result = x.pow(yint);
}
System.out.println(result);
System.out.print(prompt);
}
}
}