您的位置:首页 > 编程语言 > Java开发

java 简单的计算器(加减乘除)

2009-12-10 11:13 316 查看
import java.util.Scanner;

public class Calculator {
protected double cache1 = 0;
protected double cache2 = 0;

public static void main(String[] args) {
Calculator cor = new Calculator();
cor.calculation();
}

private void calculation() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入(例如:1+2-3*4/5=):");
String three = scanner.next();
for (int i = 0; i > -1; i++) {
String one = three.substring(i, i + 1);
boolean mat = one.matches("//d+");
if (mat) {
cache1 = Double.valueOf(one);
}
if (i == 0)
cache2 = cache1;
if (one.equals("+")) {
one = three.substring(i + 1, i + 2);
cache1 = Double.valueOf(one);
cache2 += cache1;
i++;

}
if (one.equals("-")) {
one = three.substring(i + 1, i + 2);
cache1 = Double.valueOf(one);
cache2 -= cache1;
i++;

}
if (one.equals("*")) {
one = three.substring(i + 1, i + 2);
cache1 = Double.valueOf(one);
cache2 *= cache1;
i++;

}
if (one.equals("/")) {
one = three.substring(i + 1, i + 2);
cache1 = Double.valueOf(one);
cache2 /= cache1;
i++;

}
if (one.equals("=")) {
System.out.println("运算结果:");
System.out.println(three + cache2);
break;
}
}
}
}

//刚学几天。不要见笑。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: