在Java上创建基本计算器?

时间:2016-04-24 00:09:35

标签: java

如何输入整个等式,如1 + 2.因为我只能要求用户一次输入一个数字,我想知道我如何让用户输入整个等式?

import java.util.Scanner;
public class TryCalculator {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println("Addition");
        System.out.println("Subtraction");
        System.out.println("Division");
        System.out.println("Multiplication");
        System.out.println("Natural Log");
        System.out.println("Exponent");
        System.out.println("**********************************");

       Scanner scan = new Scanner(System.in);
       Scanner keyboard = new Scanner(System.in);

       double value1;
       double value2;
       String op;

       System.out.println("enter a digit");
       value1 = scan.nextDouble();
       System.out.println("enter operation ");
       op = keyboard.next();
       System.out.println("enter second digit");
       value2 = scan.nextDouble();

        if(op.equals("+")){
            System.out.println(value1 + value2);

        }if(op.equals("-")){
            System.out.println(value1 - value2);

        }if(op.equals("/")){
            System.out.println(value1 / value2);

        }if(op.equals("*")){
            System.out.println(value1 * value2);

        }if(op.equals("^")){
            System.out.println(Math.pow(value1, value2));

        }if (op.equals("log")){
            System.out.println(Math.log(value1));

        }else{

        }  
    }   
}

1 个答案:

答案 0 :(得分:-1)

如果您不想使用javascript或某些评估者(link1link2) 你可以用1 + 2

之类的简单表达来做到这一点
Scanner keyboard = new Scanner(System.in);
String exp = keyboard.next();
    String []all = exp.split(" ", -1);
/*
then
all[0] = first operation;
all[1] = operator;
all[0] = second operator
*/

//and you can do like this
void calculate(String []all) {

    Double value1 = Double.parseDouble(all[0]);
    Double value2 = Double.parseDouble(all[2]);
    String op = all[1];

     if(op.equals("+")){
            System.out.println(value1 + value2);

    }if(op.equals("-")){
        System.out.println(value1 - value2);

    }if(op.equals("/")){
        System.out.println(value1 / value2);

    }if(op.equals("*")){
        System.out.println(value1 * value2);

    }if(op.equals("^")){
        System.out.println(Math.pow(value1, value2));

    }if (op.equals("log")){
        System.out.println(Math.log(value1));

    }else{

    }  
}

这未经过测试,但可以作为一个很好的起点。