[英]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? 如何输入一个完整的方程式,例如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{
}
}
}
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
: 如果您不想使用javascript或诸如此类的一些求值器( link1 , link2 ),则可以使用简单的表达式(如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. 这未经测试,但是可以作为一个很好的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.