实现简单的整数的相加减,不支持括号。
支持各种大数。
Task_0.0
import java.io.*;
import java.util.*;
import java.math.*;
import java.applet.*;
import java.awt.*;
import java.awt.List;
public class yyj extends Applet {
private Font f;
private String letter;
private boolean first;
private boolean second;
private char preOp;
private int xpos, ypos, cnt;
public void init() {
f = new Font("Courier", Font.BOLD, 72);
first = true;
second = false;
preOp = '+';
letter = "";
}
public void paint(Graphics g) {
g.setFont(f);
if (!first) {
g.drawString(letter, 70, 350);
}
}
// when a key is pushed down, this function will work
// key is the number of the key on the keyboard
public boolean keyDown(Event e, int key) {
first = false;
if ((char) (key) == '=') {
letter += "=" + Deal(letter);
System.out.println(letter);
repaint();
second = true;
} else {
if (second)
letter = "";
second = false;
letter += String.valueOf((char) key);
repaint();
}
return true;
}
// return the value calculated by the string s
public String Deal(String s) {
BigInteger ans = BigInteger.ZERO;
int len = s.length();
BigInteger tmp = BigInteger.ZERO;
for (int i = 0; i < len; i++) {
char Cur = s.charAt(i);
if (Cur >= '0' && Cur <= '9') {
tmp = (tmp.multiply(BigInteger.valueOf(10)));
tmp = tmp.add(BigInteger.valueOf(Cur - '0'));// a-'0';
} else if (Cur == '+' || Cur == '-') {
ans = DealNum(ans, tmp, preOp);
preOp = Cur;
tmp = BigInteger.ZERO;
} else if (Cur == '=')
break;
}
ans = DealNum(ans, tmp, preOp);
preOp = '+';
return String.valueOf(ans);
}
// do operation ,add or subtract
public BigInteger DealNum(BigInteger a, BigInteger b, char c) {
BigInteger ans = BigInteger.ZERO;
if (c == '+')
ans = a.add(b);
else if (c == '-')
ans = a.subtract(b);
return ans;
}
}