简体   繁体   中英

Creating a basic calculator on Java?

How can enter a whole equation, like 1 + 2. Because I can only so far ask the user to enter one digit at a time, I would like to know how I let the user enter the entire equation?

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{

        }  
    }   
}

If you don't want to use javascript or some evaluators like those ( link1 , link2 ) you can do like this with simple expression like 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{

    }  
}

This is not tested, but can be a good starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM